Deleting rows based on date comparison - sql - sql-server-2008

I'm writing a SQL script to remove some rows from my table.
I need to remove the rows that have a certain type (easy), where the valuation timestamp is 16:00 on the current day when the create date is less than 4pm. Does that make sense?
delete from cfo_daily_trans_hist where dh_dd_type_id = 'valuation' --and dh_val_time_stamp is today at 16:00 where the dh_create_dt is today at a time earlier than 16:00
I just don't really know the syntax to do that exact date comparison.

DELETE [dbo].[cfo_daily_trans_hist]
WHERE [dh_dd_type_id] = 'valuation'
AND [dh_val_time_stamp] = DATEADD(HH, 16, CONVERT(DATETIME,CONVERT(DATE,GETDATE()))) -- is today at 16:00
AND [the dh_create_dt] < DATEADD(HH, 16, CONVERT(DATETIME,CONVERT(DATE,GETDATE())))-- is today at a time earlier than 16:00

And dh_val_time_stamp = DateAdd(Hour, 16, DateAdd(Day, DateDiff(Day, 0, GetDate()), 0))
And dh_create_dt >= DateAdd(Day, DateDiff(Day, 0, GetDate()), 0)
And dh_create_dt < DateAdd(Hour, 16, DateAdd(Day, DateDiff(Day, 0, GetDate()), 0))

-- =================
-- sample data
-- =================
declare #t table
(
dh_val_time_stamp datetime,
dh_create_dt datetime
)
declare #d datetime
set #d = cast(cast(cast(getdate() as float) as int) as datetime)
insert into #t values (dateadd(hh, 16, #d), dateadd(hh, 14, #d))
insert into #t values (dateadd(hh, 1, #d), dateadd(hh, 2, #d))
-- =================
-- solution
-- =================
select
*
from #t t1
cross apply
(
select d = dateadd(hh, 16, cast(cast(cast(getdate() as float) as int) as datetime))
) t2
where dh_val_time_stamp = d
and dh_create_dt < d

Related

SSRS expression to calculate total based on daily counts that have conditions

In a totals row (location is row group, date is the column group), I'm not sure how to calculate a total based on the below expression that I've been using to calculate "overcapacity" daily totals. I'm trying to total up the daily overcap counts.
The below expression works fine when grouped under the "date" column grouping. So each day in the range picked by the user displays with an "overcapacity" count (if the visitscounts > 7, then the result is visitscounts - 7, otherwise it is 0).
But I'm not sure how to total up the resultant overcapacity counts (I can total up visitcounts fine). The issue is that it takes the FULL daily count and THEN applies the -7, instead of just summing all the previously calculated daily counts (if the daily account exceeds 7, then it subtracts 7 from the full daily count, to come up with an "overcapacity" count).
=IIF(SUM(IIF(Fields!Location.Value = "LOC3" OR Fields!Location.Value = "LOC4",Fields!VisitsCount.Value,0)) > 7,
SUM(SUM(IIF(Fields!Location.Value = "LOC3" OR Fields!Location.Value = "LOC4",Fields!VisitsCount.Value,0))-7),
0)
ADDITIONAL INFORMATION
Dataset Query:
SELECT
L.Location
, D.[date]
, COUNT(DISTINCT CAST(V.VisitID AS VARCHAR(10))+V.Location+V.[Room-Bed]) AS VisitsCount
FROM dbo.DateTable(#StartDate, #EndDate) AS D
CROSS JOIN (
SELECT DISTINCT Location FROM dbo.vHIMOverFlowBedReport2)
AS L LEFT JOIN dbo.vHIMOverFlowBedReport2 AS V ON D.[date] BETWEEN
V.EffectiveDate AND ISNULL(V.ServiceEndDate, #EndDate) AND V.Location = L.Location
WHERE V.EffectiveDate IS NULL OR
(V.EffectiveDate <= #EndDate OR
V.ServiceEndDate >= #StartDate OR
V.ServiceEndDate IS NULL)
GROUP BY
L.Location
, D.[date]
ORDER BY L.Location, D.[date]
OverCap New Column Testing
Dataset Query with Added OverCap Column:
SELECT
x.Location
, x.[date]
, x.VisitsCount
, OverCap = IIF(VisitsCount-7 <0 ,0, VisitsCount-7)
FROM (
SELECT
L.Location
, D.[date]
, COUNT(DISTINCT CAST(V.VisitID AS VARCHAR(10))+V.Location+V.[Room-Bed]) AS VisitsCount
FROM dbo.DateTable(#StartDate, #EndDate) AS D
CROSS JOIN (
SELECT DISTINCT Location FROM dbo.vHIMOverFlowBedReport2)
AS L LEFT JOIN dbo.vHIMOverFlowBedReport2 AS V ON D.[date] BETWEEN
V.EffectiveDate AND ISNULL(V.ServiceEndDate, #EndDate) AND V.Location = L.Location
WHERE V.EffectiveDate IS NULL OR
(V.EffectiveDate <= #EndDate OR
V.ServiceEndDate >= #StartDate OR
V.ServiceEndDate IS NULL)
GROUP BY
L.Location
, D.[date]
) x
ORDER BY x.Location, x.[date]
Full Report Layout with OverCap added
Grouped by Location (row) and [date] (column), with a totals row outside row group for combined location.
report layout
Current Resultset with OverCap Column
CurrentResultSet
NOTES:
Result for LOC3-4 is 129 (see CurrentResultSet) if I use:
OverCap = IIF(VisitsCount-7 <0 ,0, VisitsCount-7)
Result for LOC3-4 is 34 if I use:
OverCap = IIF(Location = 'LOC3' OR Location = 'LOC4', VisitsCount,0)
Result for LOC3-4 is 24 if I use:
OverCap = IIF((Location = 'LOC3' OR Location = 'LOC4') AND VisitsCount > 7, VisitsCount,0)
Expressions Used Successfully for GROUPED locations:
DailyVisitorCount (used for both DailyVisitorCount and TotalVisitorCount).
=Sum(Fields!VisitsCount.Value)
DailyOverCapacityCount (used for both DailyOverCapacityCount and TotalOverCapacityCount):
=SWITCH(
Fields!Location.Value = "LOC1" AND Fields!VisitsCount.Value > 24, SUM(Fields!VisitsCount.Value - 24),
Fields!Location.Value = "LOC2" AND Fields!VisitsCount.Value > 16, SUM(Fields!VisitsCount.Value - 16),
Fields!Location.Value = "LOC3" AND Fields!VisitsCount.Value > 7, SUM(Fields!VisitsCount.Value - 7),
Fields!Location.Value = "LOC4" AND Fields!VisitsCount.Value > 7, SUM(Fields!VisitsCount.Value - 7),
Fields!Location.Value = "LOC5" AND Fields!VisitsCount.Value > 11, SUM(Fields!VisitsCount.Value - 11),
True, 0)
Averages were calculated by using the above expressions but adding to the end:
/CountDistinct(Fields!date.Value)
Expressions Used for combined location (outside grouped location row)
DailyVisitorCount (used successfully for both DailyVisitorCount and TotalVisitorCount).
=IIF(Fields!Location.Value = "LOC3" OR Fields!Location.Value = "LOC4", Sum(Fields!VisitsCount.Value), 0)
TotalOverCapCount (used successfully with DAILY TotalOverCapCount, but not the Total TotalOverCapCount
=IIF(SUM(IIF(Fields!Location.Value = "LOC3" OR Fields!Location.Value = "LOC4",Fields!VisitsCount.Value,0)) > 7,
SUM(SUM(IIF(Fields!Location.Value = "LOC3" OR Fields!Location.Value = "LOC4",Fields!VisitsCount.Value,0))-7),
0)
Expressions still needed:
Total TotalOverCapCount (adds up daily totals for the duration)
Average TotalOverCapCount (average of daily totals for the duration)
As the expression you are trying to sum requires two scoped expression parts, it's actually difficult to then sum these.
What you need to do is
=SUM(
SUM(Fields!.MyField.Value, "ColumnGroup")
, "RowGroup")
This is probably not possible in your scenario. I abandoned the approach quickly and just updated the dataset query to return the data I needed instead
So the dataset query looked like this (using you sample data)
DECLARE #t TABLE([Location] varchar(10), [Date] Date, [VisitsCount] int)
INSERT INTO #t VALUES
('LOC1', '2022-10-31', 18), ('LOC1', '2022-11-01', 19),
('LOC1', '2022-11-02', 19), ('LOC2', '2022-10-31', 34),
('LOC2', '2022-11-01', 30), ('LOC2', '2022-11-02', 35),
('LOC3', '2022-10-31', 8), ('LOC3', '2022-11-01', 8),
('LOC3', '2022-11-02', 8), ('LOC4', '2022-10-31', 5),
('LOC4', '2022-11-01', 5), ('LOC4', '2022-11-02', 7),
('LOC5', '2022-10-31', 11), ('LOC5', '2022-11-01', 11),
('LOC5', '2022-11-02', 11)
SELECT
[Location], [Date], VisitsCount
, OverCap = IIF(VisitsCount-7 <0 ,0, VisitsCount-7)
FROM #t
As you can see, I added an OverCap column. Now all we need to do is sum that in the report.
The report design looks like this..
and the final report looks like this...
Obviously you might need to adapt this to suit whatever grouping you have going but I think it's probably a much simpler approach.
Edit after update by OP
You can wrap your original query in a SELECT and then move the order clause of of the sub query. That should give you the same results.
SELECT
[Location], [Date], VisitsCount
, OverCap = IIF(VisitsCount-7 <0 ,0, VisitsCount-7)
FROM (
SELECT
L.Location
, D.[date]
, COUNT(DISTINCT CAST(V.VisitID AS VARCHAR(10))+V.Location+V.[Room-Bed]) AS VisitsCount
FROM dbo.DateTable(#StartDate, #EndDate) AS D
CROSS JOIN (
SELECT DISTINCT Location FROM dbo.vHIMOverFlowBedReport2)
AS L LEFT JOIN dbo.vHIMOverFlowBedReport2 AS V ON D.[date] BETWEEN
V.EffectiveDate AND ISNULL(V.ServiceEndDate, #EndDate) AND V.Location = L.Location
WHERE V.EffectiveDate IS NULL OR
(V.EffectiveDate <= #EndDate OR
V.ServiceEndDate >= #StartDate OR
V.ServiceEndDate IS NULL)
GROUP BY
L.Location
, D.[date]
) x
ORDER BY [Location], [date]
If you want to just get LOC3+4 at the end of the table
Then you can do this in SQL. All I've done here is taken the existing query, dumped the results to a temp table , then returned the results plus an extra row that only contains LOC3 and LOC4 data.
Note: I added a GroupOrder column so you can sort on this in the report to make sure the combined row appears at the end.
SELECT
[Location], [Date], VisitsCount
, OverCap = IIF(VisitsCount-7 <0 ,0, VisitsCount-7)
INTO #t
FROM (
SELECT
L.Location
, D.[date]
, COUNT(DISTINCT CAST(V.VisitID AS VARCHAR(10))+V.Location+V.[Room-Bed]) AS VisitsCount
FROM dbo.DateTable(#StartDate, #EndDate) AS D
CROSS JOIN (
SELECT DISTINCT Location FROM dbo.vHIMOverFlowBedReport2)
AS L LEFT JOIN dbo.vHIMOverFlowBedReport2 AS V ON D.[date] BETWEEN
V.EffectiveDate AND ISNULL(V.ServiceEndDate, #EndDate) AND V.Location = L.Location
WHERE V.EffectiveDate IS NULL OR
(V.EffectiveDate <= #EndDate OR
V.ServiceEndDate >= #StartDate OR
V.ServiceEndDate IS NULL)
GROUP BY
L.Location
, D.[date]
) x
SELECT
GroupOrder = 1
, [Location], [Date], VisitsCount, OverCap
FROM #t
UNION ALL
SELECT
GroupOrder = 2
, [Location] = 'LOC3+4', MIN([Date]), SUM(VisitsCount), SUM(OverCap)
FROM #t
WHERE [Location] IN ('LOC3', 'LOC4')
GROUP BY YEAR([Date]), MONTH([Date])

calculate work hours in each day using mysql

I want to calculate work hours in each day using MySQL. I show many hours calculate solution but none of them fit to my requirement. In my table I don't have in our out field. I have to consider first entry as in and second as out and calculate working hours according to it.
Table structure:
CREATE TABLE IF NOT EXISTS `timesheet` (
`MachineNo` int(6) unsigned NOT NULL,
`Empcardno` int(3) unsigned NOT NULL,
`Date` date NOT NULL,
`Time` time NOT NULL
) DEFAULT CHARSET=utf8;
INSERT INTO `timesheet`
(`MachineNo`, `Empcardno`, `Date`,`Time`) VALUES
(01, 5, '2020-05-22', '18:15:54'),
(01, 5, '2020-05-22', '14:46:47'),
(01, 5, '2020-05-22', '14:26:05'),
(01, 5, '2020-05-22', '09:26:30'),
(01, 5, '2020-05-21', '18:15:45'),
(01, 5, '2020-05-21', '14:48:39'),
(01, 5, '2020-05-21', '14:29:55'),
(01, 5, '2020-05-21', '09:37:49');
MySql fiddle link
I have tried the following query but it gives me only total hours between max and min time. It does not consider all the in out values. I want to consider time between all in and out point.
SELECT
Empcardno,min(Time),
max(Time),
TIMEDIFF(max(Time),
min(Time)) As Diff_Value
FROM
timesheet
GROUP BY
DATE(Date),Empcardno
Result
Empcardno Date min(Time) max(Time) Diff_Value
5 2020-05-21 09:37:49 18:15:45 08:37:56
5 2020-05-22 09:26:30 18:15:54 08:49:24
But i want to calculate time as time between this two
(01, 5, '2020-05-21', '14:29:55'),
(01, 5, '2020-05-21', '09:37:49');
and
(01, 5, '2020-05-21', '18:15:45'),
(01, 5, '2020-05-21', '14:48:39'),
This is a tricky problem to solve without window functions... Basically you need to generate row numbers for each entry for each machine on each date. Then you can combine the odd and even rows to generate a time difference which can be summed to generate the total time for the day. To do this, I've converted the times on odd rows to negative, so that when that value is added to the next value (from the even row), we get the difference between the two.
SELECT MachineNo, Empcardno, Date, SEC_TO_TIME(SUM(tsecs)) AS total_time
FROM (
SELECT CASE WHEN MachineNo = #mn AND Empcardno = #en AND `Date` = #dt
THEN #rn := #rn + 1
ELSE #rn := 1
END AS rn,
#mn := MachineNo AS MachineNo, #en := Empcardno AS Empcardno,
#dt := `Date` AS `Date`,
CASE WHEN #rn % 2 = 1 THEN -TIME_TO_SEC(`Time`)
ELSE TIME_TO_SEC(`Time`)
END AS tsecs
FROM timesheet
CROSS JOIN (SELECT #mn := 0, #en := 0, #dt := '', #rn := 0) init
ORDER BY Date, Time
) t
GROUP BY MachineNo, Empcardno, Date
Output:
MachineNo Empcardno Date total_time
1 5 2020-05-21 08:19:12
1 5 2020-05-22 08:28:42
Demo on SQLFiddle

Creating a calendar in sql

We use a lookup table in a database for grouping weeks, months and years. Sadly the chap who created it has long since gone and the calendar runs out at the end of the year! So I really need to find a way of adding to it! Its set up with the following columns:
I'm not very good in sql(MS2008) to be honest and ive stuggeled with it, we cant set anything new up as everything is built around this!
you can do smth like this, but I don't get why your calendar starts from March?
declare #Date_Start date, #Date_End date
select #Date_Start = '20130101'
select #Date_End = '20131231'
;with
CTE_Dates as (
select #Date_Start as [Date]
union all
select dateadd(dd, 1, [Date])
from CTE_Dates
where [Date] < #Date_End
),
CTE_Calendar as (
select
[Date],
datename(dw, [Date]) as [Day],
datepart(ww, [Date]) as [Week],
datepart(mm, [Date]) as [MonthID],
dateadd(mm, datediff(mm, 0, getdate()), 0) as [Month],
datepart(yy, [Date]) as [YearID],
dateadd(yy, datediff(yy, 0, getdate()), 0) as [Year],
datepart(qq, [Date]) as [QuarterID],
dateadd(qq, datediff(qq, 0, getdate()), 0) as [Quarter]
from CTE_Dates
)
select
row_number() over (order by [Date]) + #Start_ID - 1 as ID,
*
from CTE_Calendar
option (maxrecursion 0)
SQL FIDDLE EXAMPLE

Stored Procedure Throws Error, but running as a query does not

I am aggregating data for reporting, and have a stored procedure that I am trying to insert into a temporary table. If I just run EXEC <stored_proc_name> it works just fine. However, when I try and run the following code:
Create table #TempResults2
(
slscode varchar(3),
intakes_this_month int,
intakes_this_year int,
intakes_last_month int,
intakes_two_months int,
intakes_three_months int,
intakes_four_months int,
intakes_five_months int,
intakes_six_months int,
ships_this_month int,
ships_last_month int,
ships_two_months int,
ships_three_months int,
ships_four_months int,
ships_five_months int,
ships_six_months int,
ships_this_year int
PRIMARY KEY CLUSTERED (SLSCODE)
)
INSERT INTO #TempResults2
EXEC crm.dbo.sp_sales_info
SELECT * FROM #TempResults2
DROP TABLE #TempResults2
I get the following error:
Msg 8114, Level 16, State 1, Procedure sp_sales_info, Line 36
Error converting data type varchar to int.
Warning: Null value is eliminated by an aggregate or other SET operation.
Here is my stored procedure, and I know the problem is somewhere in the first section (where I get all the shipping information) because I can comment that out and just select the intake stuff and the temp table thing works:
UPDATE here is the full stored proc
ALTER PROCEDURE [dbo].[sp_sales_info]
-- Add the parameters for the stored procedure here
AS
BEGIN
DECLARE
#today date, #this_month date, #last_month_start date, #last_month_end date,
#two_months_start date, #two_months_end date, #three_months_start date, #three_months_end date,
#four_months_start date, #four_months_end date, #five_months_start date, #five_months_end date,
#six_months_start date, #six_months_end date, #this_year_start date, #startdate date, #enddate date;
SET #today = GETDATE();
SET #this_month = DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0);
SET #last_month_start = DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()) + -1, 0);
SET #last_month_end = DATEADD(MILLISECOND, -3, DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()) + -1 + 1, 0));
SET #two_months_start = DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()) + -2, 0);
SET #two_months_end = DATEADD(MILLISECOND, -3, DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()) + -2 + 1, 0));
SET #three_months_start = DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()) + -3, 0);
SET #three_months_end = DATEADD(MILLISECOND, -3, DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()) + -3 + 1, 0));
SET #four_months_start = DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()) + -4, 0);
SET #four_months_end = DATEADD(MILLISECOND, -3, DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()) + -4 + 1, 0));
SET #five_months_start = DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()) + -5, 0);
SET #five_months_end = DATEADD(MILLISECOND, -3, DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()) + -5 + 1, 0));
SET #six_months_start = DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()) + -6, 0);
SET #six_months_end = DATEADD(MILLISECOND, -3, DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()) + -6 + 1, 0));
SET #this_year_start = CAST(DATEADD(YEAR, DATEDIFF(YEAR, 0, GETDATE()), 0) as DATE);
SET #startdate = DATEADD(YEAR, -1, GETDATE());
SET #enddate = #today;
SET NOCOUNT ON;
-- Insert statements for procedure here
SELECT
a.*,
d.intakes_this_month,
d.intakes_last_month,
d.intakes_two_months,
d.intakes_three_months,
d.intakes_four_months,
d.intakes_five_months,
d.intakes_six_months,
d.intakes_this_year
FROM
(
SELECT
sum(CASE WHEN a.SHIPDATE >= #this_month THEN 1 ELSE 0 END) AS ships_this_month,
sum(CASE WHEN a.SHIPDATE BETWEEN #last_month_start AND #last_month_end THEN 1 ELSE 0 END) AS ships_last_month,
sum(CASE WHEN a.SHIPDATE BETWEEN #two_months_start AND #two_months_end THEN 1 ELSE 0 END) AS ships_two_months,
sum(CASE WHEN a.SHIPDATE BETWEEN #three_months_start AND #three_months_end THEN 1 ELSE 0 END) AS ships_three_months,
sum(CASE WHEN a.SHIPDATE BETWEEN #four_months_start AND #four_months_end THEN 1 ELSE 0 END) AS ships_four_months,
sum(CASE WHEN a.SHIPDATE BETWEEN #five_months_start AND #five_months_end THEN 1 ELSE 0 END) AS ships_five_months,
sum(CASE WHEN a.SHIPDATE BETWEEN #six_months_start AND #six_months_end THEN 1 ELSE 0 END) AS ships_six_months,
sum(CASE WHEN a.SHIPDATE >= #this_year_start THEN 1 ELSE 0 END) AS ships_this_year,
b.slcode
FROM
(
SELECT
A.ACCOUNT AS CODE,
MIN(CAST(A.BILLDATETIME AS DATE)) AS SHIPDATE
FROM PACWARE.ADS.ARODME A
LEFT OUTER JOIN PACWARE.ADS.PTDME B ON A.PTCODE=B.CODE_
LEFT OUTER JOIN event.dbo.newdate() D ON A.ACCOUNT=D.ACCOUNT
LEFT OUTER JOIN event.dbo.newdate_extras() D2 ON A.ACCOUNT=D2.ACCOUNT
WHERE A.BILLDATETIME>=#startdate
AND A.BILLDATETIME<=#enddate
AND (
(D.NEWDATE>=#startdate AND D.NEWDATE<=#enddate) OR
(D2.NEWDATE IS NOT NULL AND D2.NEWDATE>=#startdate AND D2.NEWDATE<=#enddate) OR
B.MEDICAREID='L7900'
)
AND B.MEDICAREID IN ('A4253','L7900','A9276')
AND A.CATEGORY<>'ID'
Group by
A.ACCOUNT,
B.MEDICAREID,
A.CATEGORY
) a
JOIN event.dbo.patient_dg() b on a.CODE = b.code
GROUP BY b.slcode
) a
JOIN (
SELECT
sum(CASE WHEN a.regdate >= #this_month THEN 1 ELSE 0 END) AS intakes_this_month,
sum(CASE WHEN a.regdate BETWEEN #last_month_start AND #last_month_end THEN 1 ELSE 0 END) AS intakes_last_month,
sum(CASE WHEN a.regdate BETWEEN #two_months_start AND #two_months_end THEN 1 ELSE 0 END) AS intakes_two_months,
sum(CASE WHEN a.regdate BETWEEN #three_months_start AND #three_months_end THEN 1 ELSE 0 END) AS intakes_three_months,
sum(CASE WHEN a.regdate BETWEEN #four_months_start AND #four_months_end THEN 1 ELSE 0 END) AS intakes_four_months,
sum(CASE WHEN a.regdate BETWEEN #five_months_start AND #five_months_end THEN 1 ELSE 0 END) AS intakes_five_months,
sum(CASE WHEN a.regdate BETWEEN #six_months_start AND #six_months_end THEN 1 ELSE 0 END) AS intakes_six_months,
sum(CASE WHEN a.regdate >= #this_year_start THEN 1 ELSE 0 END) AS intakes_this_year,
a.slscode
FROM
event.dbo.patient_dg_lite() a
GROUP BY a.slscode
) d on a.slcode = d.slscode
JOIN event.dbo.employee_slscode b on a.slcode = b.slscode
JOIN event.dbo.employee c on b.employee_id = c.id
END
Your columns aren't in the same ordinal positions slscode is defined first in the CREATE TABLE.
Create table #TempResults2
(
slscode varchar(3),
/*Rest of table*/
ships_this_year int
)
But your SELECT in the stored procedure has it as the last column
SELECT
/* Loads of CASE statements*/
b.slcode
FROM /* ... */
So you are trying to insert the slscode varchar column into the integer ships_this_year column

Group by, with rank and sum - not getting correct output

I'm trying to sum a column with rank function and group by month, my code is
select dbo.UpCase( REPLACE( p.Agent_name,'.',' '))as Agent_name, SUM(convert ( float ,
p.Amount))as amount,
RANK() over( order by SUM(convert ( float ,Amount )) desc ) as arank
from dbo.T_Client_Pc_Reg p
group by p.Agent_name ,p.Sale_status ,MONTH(Reg_date)
having [p].Sale_status='Activated'
Currently I'm getting all total value of that column not month wise
Name amount rank
a 100 1
b 80 2
c 50 3
for a amount 100 is total amount till now but , i want get current month total amount not last months..
Maybe you just need to add a WHERE clause? Here is a minor re-write that I think works generally better. Some setup in tempdb:
USE tempdb;
GO
CREATE TABLE dbo.T_Client_Pc_Reg
(
Agent_name VARCHAR(32),
Amount INT,
Sale_Status VARCHAR(32),
Reg_date DATETIME
);
INSERT dbo.T_Client_Pc_Reg
SELECT 'a', 50, 'Activated', GETDATE()
UNION ALL SELECT 'a', 50, 'Activated', GETDATE()
UNION ALL SELECT 'b', 20, 'Activated', GETDATE()
UNION ALL SELECT 'b', 20, 'Activated', GETDATE()
UNION ALL SELECT 'b', 20, 'Activated', GETDATE()
UNION ALL SELECT 'b', 20, 'Activated', GETDATE()
UNION ALL SELECT 'b', 20, 'NotActivated', GETDATE()
UNION ALL SELECT 'c', 25, 'Activated', GETDATE()
UNION ALL SELECT 'c', 25, 'Activated', GETDATE()
UNION ALL SELECT 'c', 25, 'Activated', GETDATE()-40;
Then the query:
SELECT
Agent_name = UPPER(REPLACE(Agent_name, '.', '')),
Amount = SUM(CONVERT(FLOAT, Amount)),
arank = RANK() OVER (ORDER BY SUM(CONVERT(FLOAT, Amount)) DESC)
FROM dbo.T_Client_Pc_Reg
WHERE Reg_date >= DATEADD(MONTH, DATEDIFF(MONTH, 0, CURRENT_TIMESTAMP), 0)
AND Reg_date < DATEADD(MONTH, DATEDIFF(MONTH, 0, CURRENT_TIMESTAMP) + 1, 0)
AND Sale_status = 'Activated'
GROUP BY UPPER(REPLACE(Agent_name, '.', ''))
ORDER BY arank;
Now cleanup:
USE tempdb;
GO
DROP TABLE dbo.T_Client_Pc_Reg;