Related
I have static date table and a working query that I use to add references fields for comparison between financial periods, I would like to save as a view however the variable declaration is not permitted.
Query is shown below, the specific issues is with declaring "#this_qtr_month" and calculating "Is QTD". The variable determines [Num of Month in QTR] for today.
declare #this_qtr_month as int = case when month(getdate()) in (1,4,7,10) then 1
when month(getdate()) in (2,5,8,11) then 2
when month(getdate()) in (3,6,9,12) then 3
end
select *
,DATEDIFF(day,[Date],getdate()) as 'Days Aged'
,DATEDIFF(ww,[Date],getdate()) as 'Weeks Aged'
,DATEDIFF(qq,[Date],getdate()) as 'QTRs Aged'
,DATEDIFF(yy,[Date],getdate()) as 'Years Aged'
,case when DATEPART(dd,[Date]) <= DATEPART(dd,getdate()) then 'Y' else 'N' end as 'Is MTD'
,case when #this_qtr_month > [Num of Month in QTR] then 'Y'
when #this_qtr_month = [Num of Month in QTR] and DATEPART(dd,[Date]) <= DATEPART(dd,getdate()) then 'Y'
else 'N'
end as 'Is QTD'
,case when getdate() >= DATEFROMPARTS(year(getdate()), [Month Num], day(date_modified_LeapYear)) then 'Y' else 'N' end as 'Is YTD'
from Date_Table_Static
You could write that without a variable:
SELECT *,
DATEDIFF(DAY, [Date], GETDATE()) AS 'Days Aged',
DATEDIFF(ww, [Date], GETDATE()) AS 'Weeks Aged',
DATEDIFF(qq, [Date], GETDATE()) AS 'QTRs Aged',
DATEDIFF(yy, [Date], GETDATE()) AS 'Years Aged',
CASE
WHEN DATEPART(dd, [Date]) <= DATEPART(dd, GETDATE()) THEN
'Y'
ELSE
'N'
END AS 'Is MTD',
CASE
WHEN (CASE
WHEN MONTH(GETDATE()) IN ( 1, 4, 7, 10 ) THEN
1
WHEN MONTH(GETDATE()) IN ( 2, 5, 8, 11 ) THEN
2
WHEN MONTH(GETDATE()) IN ( 3, 6, 9, 12 ) THEN
3
END
) > [Num of Month in QTR] THEN
'Y'
WHEN (CASE
WHEN MONTH(GETDATE()) IN ( 1, 4, 7, 10 ) THEN
1
WHEN MONTH(GETDATE()) IN ( 2, 5, 8, 11 ) THEN
2
WHEN MONTH(GETDATE()) IN ( 3, 6, 9, 12 ) THEN
3
END
) = [Num of Month in QTR]
AND DATEPART(dd, [Date]) <= DATEPART(dd, GETDATE()) THEN
'Y'
ELSE
'N'
END AS 'Is QTD',
CASE
WHEN GETDATE() >= DATEFROMPARTS(YEAR(GETDATE()), [Month Num], DAY(date_modified_LeapYear)) THEN
'Y'
ELSE
'N'
END AS 'Is YTD'
FROM Date_Table_Static;
Or, since all you need with this view is a SELECT, you could write that as a Stored Procedure or TVF (Table Valued Function).
EDIT: I didn't read your expression before, it doesn't need to be that complex:
SELECT *,
DATEDIFF(DAY, [Date], GETDATE()) AS 'Days Aged',
DATEDIFF(ww, [Date], GETDATE()) AS 'Weeks Aged',
DATEDIFF(qq, [Date], GETDATE()) AS 'QTRs Aged',
DATEDIFF(yy, [Date], GETDATE()) AS 'Years Aged',
CASE
WHEN DATEPART(dd, [Date]) <= DATEPART(dd, GETDATE()) THEN
'Y'
ELSE
'N'
END AS 'Is MTD',
CASE
WHEN (Month(Getdate())-1)%3+1 > [Num of Month in QTR] THEN
'Y'
WHEN (Month(Getdate())-1)%3+1 = [Num of Month in QTR]
AND DATEPART(dd, [Date]) <= DATEPART(dd, GETDATE()) THEN
'Y'
ELSE
'N'
END AS 'Is QTD',
CASE
WHEN GETDATE() >= DATEFROMPARTS(YEAR(GETDATE()), [Month Num], DAY(date_modified_LeapYear)) THEN
'Y'
ELSE
'N'
END AS 'Is YTD'
FROM Date_Table_Static;
I have a requirement to check records up to differing dates, depending on which day of the week it is currently.
On a Friday I need for it to look at the entire next week, until Sunday after next. On any other day it should check the current week, up until the coming Sunday.
I have the below currently but it's not working due to syntax error. Is it possible to do a CASE WHEN inside a WHERE clause?
WHERE
T0.[Status] IN ('R','P')
AND
CASE
WHEN DATEPART(weekday,GETDATE()) = '5'
THEN T0.[DueDate] >= GETDATE() AND <= DATEADD(day, 15 - DATEPART(weekday, GetDate()), GetDate())
WHEN DATEPART(weekday, GETDATE()) != '5'
THEN T0.[DueDate] >= GETDATE() AND <= DATEADD(DAY ,8- DATEPART(weekday, GETDATE()), GETDATE())
END
It's much easier to create this logic with a series of logical or and and operators:
WHERE
T0.[Status] IN ('R','P') AND
((DATEPART(weekday,GETDATE()) = '5' AND
T0.[DueDate] >= GETDATE() AND
T0.[DueDate] <= DATEADD(day, 15 - DATEPART(weekday, GetDate()), GetDate())) OR
(DATEPART(weekday,GETDATE()) != '5' AND
T0.[DueDate] >= GETDATE() AND
T0.[DueDate] <= DATEADD(DAY ,8- DATEPART(weekday,GETDATE()),GETDATE())
)
Your syntax is wrong, you are using a condition evaluation in the THEN clause instead of an assignemnet
WHEN DATEPART(weekday,GETDATE()) = '5' THEN Your_column1 ELSE your_column2 END
......
or a inner case
CASE
WHEN DATEPART(weekday,GETDATE()) = '5' THEN
CASE WHEN T0.[DueDate] >= GETDATE()
AND <= DATEADD(day, 15 - DATEPART(weekday, GetDate()), GetDate())
THEN Your_column1 ELSE your_column2
END
END
......
I'v had a look through the forum but couldn't find anything specific enough for my scenario so here goes.
I have the following query which calculates the average time for a group of entries across multiple tables in a defined date period. The 3 types (IR, SR, CR) all are linked to a table (WorkItems). The Query I have for the average time is below. (the parameters are used in reporting services and a date picker)
Select
WIAvgAssign = AVG(
Case When WI.id Like 'IR%' Then DATEDIFF(hour,wi.CreatedDate,IR.FirstAssignedDate)
When WI.Id Like 'SR%' Then DATEDIFF(hour,wi.CreatedDate,SR.FirstAssignedDate)
When WI.Id Like 'SR%' Then DATEDIFF(hour,wi.CreatedDate,CR.FirstAssignedDate)
END),
IRAvgAssign = AVG(DATEDIFF(hour,wi.CreatedDate,IR.FirstAssignedDate)),
SRAvgAssign = AVG(DATEDIFF(hour,wi.CreatedDate,SR.FirstAssignedDate)),
CRAvgAssign = AVG(DATEDIFF(hour,wi.CreatedDate,CR.FirstAssignedDate))
from WorkItemDimvw WI
Left Outer Join IncidentDimvw IR on WI.EntityDimKey=IR.EntityDimKey
Left Outer Join ServiceRequestDimvw SR on WI.EntityDimKey=SR.EntityDimKey
Left Outer Join ChangeRequestDimvw CR on WI.EntityDimKey=CR.EntityDimKey
Where (IR.ResolvedDate >= #StartDate AND IR.ResolvedDate < #EndDate) OR
(SR.CompletedDate >= #StartDate AND SR.CompletedDate < #EndDate) OR
(CR.ActualEndDate >=#StartDate AND CR.ActualEndDate < #EndDate)
I have a table which contains each day of the week and the hours of operation for that particular day (the date is when the entry was created, it's just the time I'm interested in), the values for the weekend are blank.
Day Start Time End Time
Monday 2014-03-06 09:00:00.000 2014-03-06 17:00:00.000
Tuesday 2014-03-06 09:00:00.000 2014-03-06 17:00:00.000
Wednesday 2014-03-06 09:00:00.000 2014-03-06 17:00:00.000
Thursday 2014-03-06 09:00:00.000 2014-03-06 17:00:00.000
Friday 2014-03-06 09:00:00.000 2014-03-06 17:00:00.000
Saturday NULL NULL
Sunday NULL NULL
The average results in hours that I get currently are not specific to the hours of operation so I would like to be able to strip out when the office is closed and provide a more accurate average.
Thanks
Edit - I've come up with this, it's a bit inefficient as I've specified the number of non-working hours manually in the query and added in a calculation for weekends. Looking at the individual records I think it's correct. I've taken out the CR calculation for the time being
Declare #StartDate datetime
Declare #EndDate datetime
Set #StartDate = '2015/01/01'
Set #EndDate = '2015/12/31'
Select
AVG(
CASE WHEN CAST(wi.createddate as date) =
CAST(
CASE
WHEN WI.Id like 'IR%' then CASE WHEN ir.FirstAssignedDate !=NULL THEN ir.firstassigneddate else GETDATE() END
WHEN WI.Id like 'SR%' then CASE WHEN sr.firstassigneddate !=NULL THEN Sr.firstassigneddate else GETDATE() END
END
as date)
THEN DATEDIFF(HOUR,wi.CreatedDate,
CASE
WHEN WI.Id like 'IR%' then CASE WHEN ir.FirstAssignedDate !=NULL THEN ir.firstassigneddate else GETDATE() END
WHEN WI.Id like 'SR%' then CASE WHEN sr.firstassigneddate !=NULL THEN Sr.firstassigneddate else GETDATE() END
END)
ELSE (DATEDIFF(hour,wi.CreatedDate,DATEADD(hour,-15*DATEDIFF(day,wi.CreatedDate,CASE
WHEN WI.Id like 'IR%' then CASE WHEN ir.FirstAssignedDate !=NULL THEN ir.firstassigneddate else GETDATE() END
WHEN WI.Id like 'SR%' then CASE WHEN sr.firstassigneddate !=NULL THEN Sr.firstassigneddate else GETDATE() END
END),CASE
WHEN WI.Id like 'IR%' then CASE WHEN ir.FirstAssignedDate !=NULL THEN ir.firstassigneddate else GETDATE() END
WHEN WI.Id like 'SR%' then CASE WHEN sr.firstassigneddate !=NULL THEN Sr.firstassigneddate else GETDATE() END
END)))-48*DATEDIFF(wk,wi.CreatedDate,CASE
WHEN WI.Id like 'IR%' then CASE WHEN ir.FirstAssignedDate !=NULL THEN ir.firstassigneddate else GETDATE() END
WHEN WI.Id like 'SR%' then CASE WHEN sr.firstassigneddate !=NULL THEN Sr.firstassigneddate else GETDATE() END
END)
END)
from WorkItemDimvw WI
Left Outer Join IncidentDimvw IR on WI.EntityDimKey=IR.EntityDimKey
Left Outer Join ServiceRequestDimvw SR on WI.EntityDimKey=SR.EntityDimKey
Left Outer Join ChangeRequestDimvw CR on WI.EntityDimKey=CR.EntityDimKey
WHERE (wi.Id like 'IR%' or WI.ID like 'SR%') AND
((IR.ResolvedDate >=#StartDate AND IR.ResolvedDate < #EndDate) OR
(Sr.CompletedDate >=#StartDate AND SR.CompletedDate < #EndDate))
After many more hours of tweaking I've come up with the following which I'm 90% sure is right. If there is any way of optimising the query that would be helpful.
Declare #StartDate datetime
Declare #EndDate datetime
Set #StartDate = '2016/01/01'
Set #EndDate = '2016/12/31'
SELECT
WIAvgAssign = AVG(
Case
When id Like 'IR%' Then DATEDIFF(hour,NormalizedCreatedDate,NormalizedIRAssignedDate)
-(DATEDIFF(wk,normalizedcreateddate,NormalizedIRAssignedDate)*48)
-((DATEDIFF(day,normalizedcreateddate,NormalizedIRAssignedDate)-(DATEDIFF(wk,normalizedcreateddate,NormalizedIRAssignedDate)*2))*14)
-(Case When DateName(dw,NormalizedCreatedDate) = 'Sunday' THEN 24 ELSE 0 END)
-(Case When DATENAME(dw,NormalizedIRAssignedDate) = 'Saturday' THEN 24 ELSE 0 END)
When id Like 'SR%' Then DATEDIFF(hour,NormalizedCreatedDate,NormalizedSRAssignedDate)
-(DATEDIFF(wk,normalizedcreateddate,NormalizedSRAssignedDate)*48)
-((DATEDIFF(day,normalizedcreateddate,NormalizedSRAssignedDate)-(DATEDIFF(wk,normalizedcreateddate,NormalizedSRAssignedDate)*2))*14)
-(Case When DateName(dw,NormalizedCreatedDate) = 'Sunday' THEN 24 ELSE 0 END)
-(Case When DATENAME(dw,NormalizedSRAssignedDate) = 'Saturday' THEN 24 ELSE 0 END)
When id Like 'CR%' Then DATEDIFF(hour,NormalizedCreatedDate,NormalizedCRAssignedDate)
-(DATEDIFF(wk,normalizedcreateddate,NormalizedCRAssignedDate)*48)
-((DATEDIFF(day,normalizedcreateddate,NormalizedCRAssignedDate)-(DATEDIFF(wk,normalizedcreateddate,NormalizedCRAssignedDate)*2))*14)
-(Case When DateName(dw,NormalizedCreatedDate) = 'Sunday' THEN 24 ELSE 0 END)
-(Case When DATENAME(dw,NormalizedCRAssignedDate) = 'Saturday' THEN 24 ELSE 0 END)
END),
IRAvgAssign = AVG(DATEDIFF(hour,NormalizedCreatedDate,NormalizedIRAssignedDate)
-(DATEDIFF(wk,normalizedcreateddate,NormalizedIRAssignedDate)*48)
-((DATEDIFF(day,normalizedcreateddate,NormalizedIRAssignedDate)-(DATEDIFF(wk,normalizedcreateddate,NormalizedIRAssignedDate)*2))*14)
-(Case When DateName(dw,NormalizedCreatedDate) = 'Sunday' THEN 24 ELSE 0 END)
-(Case When DATENAME(dw,NormalizedIRAssignedDate) = 'Saturday' THEN 24 ELSE 0 END)),
SRAvgAssign = AVG(DATEDIFF(hour,NormalizedCreatedDate,NormalizedSRAssignedDate)
-(DATEDIFF(wk,normalizedcreateddate,NormalizedSRAssignedDate)*48)
-((DATEDIFF(day,normalizedcreateddate,NormalizedSRAssignedDate)-(DATEDIFF(wk,normalizedcreateddate,NormalizedSRAssignedDate)*2))*14)
-(Case When DateName(dw,NormalizedCreatedDate) = 'Sunday' THEN 24 ELSE 0 END)
-(Case When DATENAME(dw,NormalizedSRAssignedDate) = 'Saturday' THEN 24 ELSE 0 END)),
CRAvgAssign = AVG(DATEDIFF(hour,NormalizedCreatedDate,NormalizedCRAssignedDate)
-(DATEDIFF(wk,normalizedcreateddate,NormalizedCRAssignedDate)*48)
-((DATEDIFF(day,normalizedcreateddate,NormalizedCRAssignedDate)-(DATEDIFF(wk,normalizedcreateddate,NormalizedCRAssignedDate)*2))*14)
-(Case When DateName(dw,NormalizedCreatedDate) = 'Sunday' THEN 24 ELSE 0 END)
-(Case When DATENAME(dw,NormalizedCRAssignedDate) = 'Saturday' THEN 24 ELSE 0 END))
FROM (
Select WI.id,
CASE
WHEN wi.CreatedDate < DATEADD(HOUR, 9, CAST(CAST(wi.CreatedDate AS DATE) AS DATETIME))
THEN DATEADD(HOUR, 9, CAST(CAST(wi.CreatedDate AS DATE) AS DATETIME))
ELSE wi.CreatedDate
END NormalizedCreatedDate,
CASE
WHEN IR.FirstAssignedDate !=NULL THEN CASE
WHEN IR.FirstAssignedDate > DATEADD(HOUR, 17, CAST(CAST(IR.FirstAssignedDate AS DATE) AS DATETIME))
THEN DATEADD(HOUR, 17, CAST(CAST(IR.FirstAssignedDate AS DATE) AS DATETIME))
ELSE IR.FirstAssignedDate END
ELSE CASE WHEN IR.ResolvedDate > DATEADD(HOUR, 17, CAST(CAST(IR.ResolvedDate AS DATE) AS DATETIME))
THEN DATEADD(HOUR, 17, CAST(CAST(IR.ResolvedDate AS DATE) AS DATETIME))
ELSE IR.ResolvedDate END
END NormalizedIRAssignedDate,
CASE
WHEN SR.FirstAssignedDate !=NULL THEN CASE
WHEN SR.FirstAssignedDate > DATEADD(HOUR, 17, CAST(CAST(SR.FirstAssignedDate AS DATE) AS DATETIME))
THEN DATEADD(HOUR, 17, CAST(CAST(SR.FirstAssignedDate AS DATE) AS DATETIME))
ELSE SR.FirstAssignedDate END
ELSE CASE WHEN SR.CompletedDate > DATEADD(HOUR, 17, CAST(CAST(SR.CompletedDate AS DATE) AS DATETIME))
THEN DATEADD(HOUR, 17, CAST(CAST(SR.CompletedDate AS DATE) AS DATETIME))
ELSE SR.CompletedDate END
END NormalizedSRAssignedDate,
CASE
WHEN CR.FirstAssignedDate !=NULL THEN CASE
WHEN CR.FirstAssignedDate > DATEADD(HOUR, 17, CAST(CAST(CR.FirstAssignedDate AS DATE) AS DATETIME))
THEN DATEADD(HOUR, 17, CAST(CAST(CR.FirstAssignedDate AS DATE) AS DATETIME))
ELSE CR.FirstAssignedDate END
ELSE CASE WHEN CR.ActualEndDate > DATEADD(HOUR, 17, CAST(CAST(CR.ActualEndDate AS DATE) AS DATETIME))
THEN DATEADD(HOUR, 17, CAST(CAST(CR.ActualEndDate AS DATE) AS DATETIME))
ELSE CR.ActualEndDate END
END NormalizedCRAssignedDate
from WorkItemDimvw WI
Left Outer Join IncidentDimvw IR
on WI.EntityDimKey=IR.EntityDimKey
Left Outer Join ServiceRequestDimvw SR
on WI.EntityDimKey=SR.EntityDimKey
Left Outer Join ChangeRequestDimvw CR
on WI.EntityDimKey=CR.EntityDimKey
Where (
(IR.ResolvedDate >= #StartDate AND IR.ResolvedDate < #EndDate)
OR (SR.CompletedDate >= #StartDate AND SR.CompletedDate < #EndDate)
OR (CR.ActualEndDate >= #StartDate AND CR.ActualEndDate < #EndDate)
)
) dataset
Edit - obviously we weren't excluding the time after 5pm (it's between 8 and 6 in my example as that's what my customer wanted) so I added in a calculation to remove 14 hours for every day (apart from weekends) the item is open which has given me what I believe to be the exact figures
This has been an intriguing question for me. I assumed a few things in my approach to this one:
CreatedDate always happens before FirstAssignedDate
SET DATEFIRST 7 (changes weekday numbers if different)
That is is okay to filter out CreatedDate and FirstAssignedDate if they are on a weekend
Here's my approach and I'm sure that it's wildly inefficient, but it was my first idea:
SELECT
WIAvgAssign = AVG(
Case
When id Like 'IR%' Then DATEDIFF(hour,NormalizedCreatedDate,NormalizedIRAssignedDate)
When id Like 'SR%' Then DATEDIFF(hour,NormalizedCreatedDate,NormalizedSRAssignedDate)
When id Like 'SR%' Then DATEDIFF(hour,NormalizedCreatedDate,NormalizedCRAssignedDate)
END
),
IRAvgAssign = AVG(DATEDIFF(hour,NormalizedCreatedDate,NormalizedIRAssignedDate)),
SRAvgAssign = AVG(DATEDIFF(hour,NormalizedCreatedDate,NormalizedSRAssignedDate)),
CRAvgAssign = AVG(DATEDIFF(hour,NormalizedCreatedDate,NormalizedCRAssignedDate))
FROM (
Select WI.id,
CASE
WHEN wi.CreatedDate < DATEADD(HOUR, 9, CAST(CAST(wi.CreatedDate AS DATE) AS DATETIME))
THEN DATEADD(HOUR, 9, CAST(CAST(wi.CreatedDate AS DATE) AS DATETIME))
ELSE wi.CreatedDate
END NormalizedCreatedDate,
CASE
WHEN IR.FirstAssignedDate > DATEADD(HOUR, 17, CAST(CAST(IR.FirstAssignedDate AS DATE) AS DATETIME))
THEN DATEADD(HOUR, 17, CAST(CAST(IR.FirstAssignedDate AS DATE) AS DATETIME))
ELSE IR.FirstAssignedDate
END NormalizedIRAssignedDate,
CASE
WHEN SR.FirstAssignedDate > DATEADD(HOUR, 17, CAST(CAST(SR.FirstAssignedDate AS DATE) AS DATETIME))
THEN DATEADD(HOUR, 17, CAST(CAST(SR.FirstAssignedDate AS DATE) AS DATETIME))
ELSE SR.FirstAssignedDate
END NormalizedSRAssignedDate,
CASE
WHEN CR.FirstAssignedDate > DATEADD(HOUR, 17, CAST(CAST(CR.FirstAssignedDate AS DATE) AS DATETIME))
THEN DATEADD(HOUR, 17, CAST(CAST(CR.FirstAssignedDate AS DATE) AS DATETIME))
ELSE CR.FirstAssignedDate
END NormalizedCRAssignedDate
from WorkItemDimvw WI
Left Outer Join IncidentDimvw IR
on WI.EntityDimKey=IR.EntityDimKey
Left Outer Join ServiceRequestDimvw SR
on WI.EntityDimKey=SR.EntityDimKey
Left Outer Join ChangeRequestDimvw CR
on WI.EntityDimKey=CR.EntityDimKey
--AVOID SATURDAYS and SUNDAYS in result set
--Also assumes SET DATEFIRST 7
Where DATEPART(WEEKDAY,wi.CreatedDate) NOT IN (1,7)
AND DATEPART(WEEKDAY,IR.FirstAssignedDate) NOT IN (1,7)
AND DATEPART(WEEKDAY,SR.FirstAssignedDate) NOT IN (1,7)
AND DATEPART(WEEKDAY,CR.FirstAssignedDate) NOT IN (1,7)
AND(
(IR.ResolvedDate >= #StartDate AND IR.ResolvedDate < #EndDate)
OR (SR.CompletedDate >= #StartDate AND SR.CompletedDate < #EndDate)
OR (CR.ActualEndDate >= #StartDate AND CR.ActualEndDate < #EndDate)
)
) dataset
So I basically just check if the CreatedDate < 0900 of the same day and set the time to 0900 if that is the case, and then I check if FirstAssignedDate > 1700 of the same day and set the time to 1700 if that is the case. I also filtered out all of the CreatedDates and FirstAssignedDates if they were on a weekend.
EDIT:
I updated the my original post. I changed the date checks to use DATEADD rather than building a string and trying to convert the string to a DATETIME
I want to condense the following three queries into one query and out put the totals into 3 columns. Oh and how do I make it so I don't have to declare the date. I want it to "know" the current date, month, and year.
DECLARE #myDate as datetime
SET #myDate = '2015-01-1'
select SUM(Amount) as 'Day Total'
from [Accounting].[dbo].[HandPay]
where AccountingDate>=#myDate and AccountingDate<dateadd(day,1,#myDate)
select SUM(Amount) as 'Month Total'
from [Accounting].[dbo].[HandPay]
where AccountingDate>=#myDate and AccountingDate<dateadd(MONTH,1,#myDate)
select SUM(Amount) as 'Day Total'
from [Accounting].[dbo].[HandPay]
where AccountingDate>=#myDate and AccountingDate<dateadd(year,1,#myDate)
What is the best way to do this?
Thanks!
Thanks for all the super fast responses! This is now solved.
If I'm understanding the problem correctly, then something like this ought to work:
declare #today date = convert(date, getdate());
select
[Day Total] = sum(case when [AccountingDate] >= #today and [AccountingDate] < dateadd(day, 1, #today) then [Amount] else 0 end),
[Month Total] = sum(case when [AccountingDate] >= #today and [AccountingDate] < dateadd(month, 1, #today) then [Amount] else 0 end),
[Year Total] = sum(case when [AccountingDate] >= #today and [AccountingDate] < dateadd(year, 1, #today) then [Amount] else 0 end)
from
[Accounting].[dbo].[HandPay];
Note that [Month Total] and [Year Total] don't give the sums of the entries that occur within the current month/year, but rather the sum of the entries that occur within a month/a year of today's date. I'm not sure if that's what you want, but it seems consistent with the original queries.
UPDATE: As suggested by D Stanley below, you can simplify this a bit since you know that the date ranges that compose the [Day Total] and [Month Total] sums are enclosed entirely within the date range that composes the [Year Total] sum. Here's what this might look like:
declare #today date = convert(date, getdate());
select
[Day Total] = sum(case when [AccountingDate] < dateadd(day, 1, #today) then [Amount] else 0 end),
[Month Total] = sum(case when [AccountingDate] < dateadd(month, 1, #today) then [Amount] else 0 end),
[Year Total] = sum([Amount])
from
[Accounting].[dbo].[HandPay]
where
[AccountingDate] >= #today and [AccountingDate] < dateadd(year, 1, #today);
Make them all part of a 'super' select:
DECLARE #myDate as datetime
SET #myDate = '2015-01-1'
SELECT
(select SUM(Amount)
from [Accounting].[dbo].[HandPay]
where AccountingDate>=#myDate and AccountingDate<dateadd(day,1,#myDate) ) as 'Day Total',
(select SUM(Amount)
from [Accounting].[dbo].[HandPay]
where AccountingDate>=#myDate and AccountingDate<dateadd(MONTH,1,#myDate) ) as 'Month Total',
(select SUM(Amount)
from [Accounting].[dbo].[HandPay]
where AccountingDate>=#myDate and AccountingDate<dateadd(year,1,#myDate) ) as 'Day Total'
One way is to write each as a sub-query with a surrounding select. I have often found this useful as it allows me to piece together the query one bit at a time. This will give you null in the column values when there is no records - which may not be what you want. Refer to #JoeFarrell's question as he has provided an example of using case to turn null into 0.
(Please excuse the strange layout, felt it was worth accentuating the ,)
DECLARE #myDate as datetime
SET #myDate = '2015-01-1'
select
(select SUM(sale_total)
from [Accounting].[dbo].[HandPay]
where AccountingDate>=#myDate and AccountingDate<dateadd(day,1,#myDate)) as 'Day Total'
,
(select SUM(sale_total)
from [Accounting].[dbo].[HandPay]
where AccountingDate>=#myDate and AccountingDate<dateadd(MONTH,1,#myDate)) as 'Month Total'
,
(select SUM(sale_total)
from [Accounting].[dbo].[HandPay]
where AccountingDate>=#myDate and AccountingDate<dateadd(year,1,#myDate)) as 'Day Total'
I have a query where i need to get values in 4 columns but only if the date is greater than today from a 5th column. I have tried the following but it doesn't seem to be working.
Select
(case when clientplans.END_DATE < convert(date,getdate(,101) then '') else insplans.Desc_upper as PLAN NAME,
(case when clientplans.END_DATE < convert(date,getdate(,112) then '') else insplans.ID_NO,
(case when clientplans.END_DATE < convert(date,getdate(,112) then '') else insplans.cert_NO,
I have converted the date on the end date as follows:
convert (varchar,clientplans.END_DATE,112) as POLICY_EXP_DATE,
does it matter that I do the conversion of the end date later in the query? the clientplans.end_date has to be inserted into the results in a certain order which happens to be after the description, id and cert number. Thanks for any help.
Perhaps something like this does what you want:
Select (case when cp.END_DATE > cast(getdate() as date) then insplans.Desc_upper end) as PLAN_NAME,
(case when cp.END_DATE > cast(getdate() as date) then insplans.ID_NO end) as ID_NO,
(case when cp.END_DATE > cast(getdate() as date) then insplans.cert_NO END) as cert_NO
from clientplans cp . . .
Note the following:
This table uses table aliases (cp for clientplans), so the query is easier to write and to read.
It uses cast() to a date to just get the date.
Non-matching rows are given a NULL value instead of ''. That usually makes more sense.
EDIT:
Of course, you can use '', if you like:
Select (case when cp.END_DATE > cast(getdate() as date) then insplans.Desc_upper else '' end) as PLAN_NAME,
(case when cp.END_DATE > cast(getdate() as date) then insplans.ID_NO else '' end) as ID_NO,
(case when cp.END_DATE > cast(getdate() as date) then insplans.cert_NO else '' end) as cert_NO,
(case when cp.END_DATE > cast(getdate() as date)
then convert(varchar(255), cp.StartDate, 121) else ''
end) as StartDate
from clientplans cp . . .
Use this to get the start of today: DATEADD(day, DATEDIFF(day, 0, GETDATE()), 0)
For example:
SELECT DATEADD(day, DATEDIFF(day, 0, GETDATE()), 0)
And for yours...
Select
(case when clientplans.END_DATE > DATEADD(day, DATEDIFF(day, 0, GETDATE()), 0) then '') else insplans.Desc_upper as PLAN NAME,
(case when clientplans.END_DATE > DATEADD(day, DATEDIFF(day, 0, GETDATE()), 0) then '') else insplans.ID_NO,
(case when clientplans.END_DATE > DATEADD(day, DATEDIFF(day, 0, GETDATE()), 0) then '') else insplans.cert_NO,
i think proper casting is required So I Used Here CAST(Field as DATE) and
in Your Query getdate(,101) is wrong syntax
Select
(case when CAST(clientplans.END_DATE as date) < CAST(getdate() as date) then '')
else insplans.Desc_upper as PLAN NAME,
(case when CAST(clientplans.END_DATE as date) < CAST(getdate() as date) then '')
else insplans.ID_NO,
(case when CAST(clientplans.END_DATE as date) < CAST(getdate() as date) then '')
else insplans.cert_NO
You can use cursor on the 5th column
and check #cursor_date> is greater than today.
Only then will get the rest of the 4 columns.