SQL Grouping and DATEDIFF Issue - sql

The query below is using Axosoft's OnTime DB with a few custom fields. If you ignore the custom fields and have some sample data this should work.
What I'm trying to do:
Return a query that has a count(total) number of open tickets that have been open during these time frames:
Less than a day
1 Day
2 Days
3 Days
4 Days
5 Days
6 Days
More than a week
this is for a ticket aging query. Here's the query below:
DECLARE #endDate DateTime;
SET #endDate = '03/18/2011';
WITH
WorkItems AS
(
SELECT
i.ProjectID AS ProjectID,
CASE WHEN ic.Custom_279 = 'Bug' THEN 'Issue' WHEN ic.Custom_279 IS NULL THEN 'Other' WHEN LTRIM(RTRIM(ic.Custom_279)) = '' THEN 'Other' ELSE ic.Custom_279 END AS WorkItemType,
i.IncidentNumber AS ID,
i.Name AS Name,
--CASE WHEN ic.Custom_264 < '1901-01-01' THEN NULL ELSE ic.Custom_264 END AS DateReported,
CASE WHEN i.CreatedDateTime < '1901-01-01' THEN NULL ELSE i.CreatedDateTime END AS DateReported,
CASE WHEN ic.Custom_265 < '1901-01-01' THEN NULL ELSE ic.Custom_265 END AS DateResolutionBegan,
CASE WHEN ic.Custom_266 < '1901-01-01' THEN NULL ELSE ic.Custom_266 END AS DateSignoffRequested,
CASE WHEN ic.Custom_267 < '1901-01-01' THEN NULL ELSE ic.Custom_267 END AS DateClosed
FROM
dbo.Incidents AS i
INNER JOIN dbo.IncidentCustomFields AS ic ON ic.IncidentID = i.IncidentID
WHERE
i.Archived = 0
),
ProjectDescendantsIncludingSelf AS
(
SELECT
p.ProjectID AS ProjectID,
p.ProjectID AS DescendantProjectID,
CAST('/' + p.Name AS NVARCHAR) AS ProjectPath
FROM
dbo.Projects AS p
UNION ALL
SELECT
pd.ProjectID AS ProjectID,
p.ProjectID AS DescendantProjectID,
CAST(pd.ProjectPath + N'/' + p.Name AS NVARCHAR) AS ProjectPath
FROM
ProjectDescendantsIncludingSelf AS pd
INNER JOIN dbo.Projects AS p ON p.ParentID = pd.DescendantProjectID
),
OpenTicketsLessThanDay AS
(SELECT
COUNT(ID) AS [LessThanDayTicketCount],
CASE WHEN DATEDIFF(DAY, DateReported, #endDate) < 1 THEN DATEDIFF(DAY, DateReported, #endDate) ELSE NULL END AS [LessThanDay],
--CASE WHEN (DATEDIFF(DAY, DateReported, #endDate) > 1) AND (DATEDIFF(DAY, DateReported, #endDate) <= 2) THEN DATEDIFF(DAY, DateReported, #endDate) ELSE NULL END AS [GreaterThan1Day],
--CASE WHEN (DATEDIFF(DAY, DateReported, #endDate) > 2) AND (DATEDIFF(DAY, DateReported, #endDate) <= 3) THEN DATEDIFF(DAY, DateReported, #endDate) ELSE NULL END AS [GreaterThan2Days],
--CASE WHEN (DATEDIFF(DAY, DateReported, #endDate) > 3) AND (DATEDIFF(DAY, DateReported, #endDate) <= 4) THEN DATEDIFF(DAY, DateReported, #endDate) ELSE NULL END AS [GreaterThan3Days],
--CASE WHEN (DATEDIFF(DAY, DateReported, #endDate) > 4) AND (DATEDIFF(DAY, DateReported, #endDate) <= 5) THEN DATEDIFF(DAY, DateReported, #endDate) ELSE NULL END AS [GreaterThan4Days],
--CASE WHEN (DATEDIFF(DAY, DateReported, #endDate) > 5) AND (DATEDIFF(DAY, DateReported, #endDate) <= 6) THEN DATEDIFF(DAY, DateReported, #endDate) ELSE NULL END AS [GreaterThan5Days],
--CASE WHEN (DATEDIFF(DAY, DateReported, #endDate) > 6) AND (DATEDIFF(DAY, DateReported, #endDate) <= 7) THEN DATEDIFF(DAY, DateReported, #endDate) ELSE NULL END AS [GreaterThan6Days],
--CASE WHEN DATEDIFF(WEEK, DateReported, #endDate) > 1 THEN DATEDIFF(DAY, DateReported, #endDate) ELSE NULL END AS [GreaterThanWeek],
--DateReported,
--DateClosed,
--d.ProjectPath
FROM WorkItems wi
INNER JOIN ProjectDescendantsIncludingSelf d ON d.DescendantProjectID = wi.ProjectID
WHERE
DateReported < #endDate AND
(DateClosed IS NULL OR DateClosed > #endDate) AND
d.ProjectID = 182 AND
d.DescendantProjectID != 185
GROUP BY LessThanDay
)
SELECT [LessThanDayTicketCount] FROM OpenTicketsLessThanDay
GROUP BY LessThanDay
ORDER BY LessThanDay ASC

I presume you need something like one or the other of these.
DECLARE #EndDate datetime = getdate()
SELECT
COUNT(CASE WHEN modify_date > DATEADD(DAY,-1,#EndDate) THEN 1 END) AS [LessThanDay],
COUNT(CASE WHEN modify_date > DATEADD(DAY,-2,#EndDate) AND modify_date <= DATEADD(DAY,-1,#EndDate) THEN 1 END) AS [GreaterThan1Day],
COUNT(CASE WHEN modify_date > DATEADD(DAY,-3,#EndDate) AND modify_date <= DATEADD(DAY,-2,#EndDate) THEN 1 END) AS [GreaterThan2Days],
COUNT(CASE WHEN modify_date > DATEADD(DAY,-4,#EndDate) AND modify_date <= DATEADD(DAY,-3,#EndDate) THEN 1 END) AS [GreaterThan3Days],
COUNT(CASE WHEN modify_date > DATEADD(DAY,-5,#EndDate) AND modify_date <= DATEADD(DAY,-4,#EndDate) THEN 1 END) AS [GreaterThan4Days],
COUNT(CASE WHEN modify_date > DATEADD(DAY,-6,#EndDate) AND modify_date <= DATEADD(DAY,-5,#EndDate) THEN 1 END) AS [GreaterThan5Days],
COUNT(CASE WHEN modify_date > DATEADD(DAY,-7,#EndDate) AND modify_date <= DATEADD(DAY,-6,#EndDate) THEN 1 END) AS [GreaterThan6Days],
COUNT(CASE WHEN modify_date <= DATEADD(DAY,-7,#EndDate) THEN 1 END) AS [GreaterThanWeek]
FROM sys.objects
WHERE modify_date <= #EndDate
SELECT
COUNT(CASE WHEN DATEDIFF(DAY, modify_date, #EndDate) = 0 THEN 1 END) AS [LessThanDay],
COUNT(CASE WHEN DATEDIFF(DAY, modify_date, #EndDate) = 1 THEN 1 END) AS [GreaterThan1Day],
COUNT(CASE WHEN DATEDIFF(DAY, modify_date, #EndDate) = 2 THEN 1 END) AS [GreaterThan2Days],
COUNT(CASE WHEN DATEDIFF(DAY, modify_date, #EndDate) = 3 THEN 1 END) AS [GreaterThan3Days],
COUNT(CASE WHEN DATEDIFF(DAY, modify_date, #EndDate) = 4 THEN 1 END) AS [GreaterThan4Days],
COUNT(CASE WHEN DATEDIFF(DAY, modify_date, #EndDate) = 5 THEN 1 END) AS [GreaterThan5Days],
COUNT(CASE WHEN DATEDIFF(DAY, modify_date, #EndDate) = 6 THEN 1 END) AS [GreaterThan6Days],
COUNT(CASE WHEN DATEDIFF(DAY, modify_date, #EndDate) > 6 THEN 1 END) AS [GreaterThanWeek]
FROM sys.objects
WHERE modify_date <= #EndDate

Related

Get the last 14 days of records not included current date

I'm having trouble with the dates. I have here my code to count the records for the last 14 days from the current date but not including TODAY in the display.
Here's my SQL query
SELECT
a.TrackingCode,
a.SegmentName,
a.Brand,
a.DateAdded,
COUNT(CASE WHEN DATEDIFF(DD, a.DateAdded, GETDATE()) = 1 THEN 1 ELSE NULL END) as "Day_1",
COUNT(CASE WHEN DATEDIFF(DD, a.DateAdded, GETDATE()) = 2 THEN 1 ELSE NULL END) as "Day_2",
COUNT(CASE WHEN DATEDIFF(DD, a.DateAdded, GETDATE()) = 3 THEN 1 ELSE NULL END) as "Day_3",
COUNT(CASE WHEN DATEDIFF(DD, a.DateAdded, GETDATE()) = 4 THEN 1 ELSE NULL END) as "Day_4",
COUNT(CASE WHEN DATEDIFF(DD, a.DateAdded, GETDATE()) = 5 THEN 1 ELSE NULL END) as "Day_5",
COUNT(CASE WHEN DATEDIFF(DD, a.DateAdded, GETDATE()) = 6 THEN 1 ELSE NULL END) as "Day_6",
COUNT(CASE WHEN DATEDIFF(DD, a.DateAdded, GETDATE()) = 7 THEN 1 ELSE NULL END) as "Day_7",
COUNT(CASE WHEN DATEDIFF(DD, a.DateAdded, GETDATE()) = 8 THEN 1 ELSE NULL END) as "Day_8",
COUNT(CASE WHEN DATEDIFF(DD, a.DateAdded, GETDATE()) = 9 THEN 1 ELSE NULL END) as "Day_9",
COUNT(CASE WHEN DATEDIFF(DD, a.DateAdded, GETDATE()) = 10 THEN 1 ELSE NULL END) as "Day_10",
COUNT(CASE WHEN DATEDIFF(DD, a.DateAdded, GETDATE()) = 11 THEN 1 ELSE NULL END) as "Day_11",
COUNT(CASE WHEN DATEDIFF(DD, a.DateAdded, GETDATE()) = 12 THEN 1 ELSE NULL END) as "Day_12",
COUNT(CASE WHEN DATEDIFF(DD, a.DateAdded, GETDATE()) = 13 THEN 1 ELSE NULL END) as "Day_13",
COUNT(CASE WHEN DATEDIFF(DD, a.DateAdded, GETDATE()) = 14 THEN 1 ELSE NULL END) as "Day_14"
FROM
Journey_Injection_Logger_Base a
WHERE
a.DateAdded >= DATEADD(DD, -14, GETDATE())
AND a.DateAdded <= GETDATE()
GROUP BY
a.TrackingCode, a.SegmentName, a.Brand, a.DateAdded
The Day_1 is the yesterday's date. The problem is that when the next day comes it will add the new current date and my records for the Day_1 is not moving.
Sample output
enter image description here
From the above image of sample output. The record 2 should be in 4/14 TUE

Using Count with Case expression

I'm probably going to torn apart for asking but why do these produce different results when comparing Claims_Completed in the 2 different scenarios? The Claims_Completed values are the same as Claims_Received in both scenarios.
SELECT
DischargeType
,COUNT(CASE WHEN (DateReceived > '2/1/2015' AND DateReceived < DATEADD(dd, 1, '2/28/2015')) THEN 1 ELSE 0 END) AS Claims_Received
,COUNT(CASE WHEN (DateCompleted > '2/1/2015' AND DateCompleted < DATEADD(dd, 1, '2/28/2015')) THEN 1 ELSE 0 END) AS Claims_Completed
FROM Claims GROUP BY DischargeType
Scenario 2:
SELECT COUNT(*) AS Claims_Received
FROM Claims
WHERE DateReceived > '2/1/2015' AND DateReceived < DATEADD(dd, 1, '2/28/2015')
GROUP BY DischargeType
SELECT COUNT(*) AS Claims_Completed
FROM Claims
WHERE DateCompleted > '2/1/2015' AND DateCompleted < DATEADD(dd, 1, '2/28/2015')
GROUP BY DischargeType
You need sum() instead of count():
SELECT DischargeType,
SUM(CASE WHEN (DateReceived > '2/1/2015' AND
DateReceived < DATEADD(dd, 1, '2/28/2015'))
THEN 1 ELSE 0
END) AS Claims_Received,
SUM(CASE WHEN (DateCompleted > '2/1/2015' AND
DateCompleted < DATEADD(dd, 1, '2/28/2015'))
THEN 1 ELSE 0
END) AS Claims_Completed
FROM Claims
GROUP BY DischargeType;
Because count() misinterpret here, as it will count 0 as value or as data.
COUNT will count all non-null values from the sequence. Since 1 and 0 are both non-null it's counting everything. One option is to use NULL instead of 0:
SELECT
DischargeType
,COUNT(CASE WHEN (DateReceived > '2/1/2015'
AND DateReceived < DATEADD(dd, 1, '2/28/2015'))
THEN 1 ELSE NULL END) AS Claims_Received
,COUNT(CASE WHEN (DateCompleted > '2/1/2015'
AND DateCompleted < DATEADD(dd, 1, '2/28/2015'))
THEN 1 ELSE NULL END) AS Claims_Completed
FROM Claims
GROUP BY DischargeType

efficient way to write this query - audit histroy on created and modified

just wondering if there is a better and more efficient way of creating this query as the below is taking a long time as this query is being run for every table in the database catalogue. Thank you
Select N'MSCRM_REPORTING' As [Database], N'dbo' As [Schema], N'apuk_erqanswerBase' As [Table], N'ModifiedOn' As ChangeType,
sum(case when DATEADD(dd, DATEDIFF(dd, 0,ModifiedOn), 0) between DATEADD(dd, DATEDIFF(dd, 0, getdate()), 0) -7 AND DATEADD(dd, DATEDIFF(dd, 0, getdate()), 0) THEN 1 ELSE 0 END) [0-7 Days],
sum(case when DATEADD(dd, DATEDIFF(dd, 0,ModifiedOn), 0) between DATEADD(dd, DATEDIFF(dd, 0, getdate()), 0)-28 AND DATEADD(dd, DATEDIFF(dd, 0, getdate()), 0)- 8 THEN 1 ELSE 0 END) [8-28 Days],
sum(case when DATEADD(dd, DATEDIFF(dd, 0,ModifiedOn), 0) between DATEADD(dd, DATEDIFF(dd, 0, getdate()), 0)-84 AND DATEADD(dd, DATEDIFF(dd, 0, getdate()), 0)-29 THEN 1 ELSE 0 END) [29-84 Days],
sum(case when DATEADD(dd, DATEDIFF(dd, 0,ModifiedOn), 0) between DATEADD(dd, DATEDIFF(dd, 0, getdate()), 0)-182 AND DATEADD(dd, DATEDIFF(dd, 0, getdate()), 0)-85 THEN 1 ELSE 0 END) [85-182 Days],
sum(case when DATEADD(dd, DATEDIFF(dd, 0, ModifiedOn), 0) BETWEEN convert(datetime,0) and DATEADD(dd, DATEDIFF(dd, 0, getdate()), 0) - 183 THEN 1 ELSE 0 END) [183+],
sum(case when ModifiedOn is null then 1 else 0 end) [NullRows],
count(*) as [RowCount]
From MSCRM_REPORTING.dbo.apuk_erqanswerBase
Having multiple DATEDIFFs will be costly, so why not try getting the difference between the dates in a subquery and using that within the SELECT:
Select N'MSCRM_REPORTING' As [Database], N'dbo' As [Schema], N'apuk_erqanswerBase' As [Table], N'ModifiedOn' As ChangeType,
sum(case when a.Days BETWEEN 0 AND 7 THEN 1 ELSE 0 END) [0-7 Days],
sum(case when a.Days BETWEEN 8 AND 28 THEN 1 ELSE 0 END) [8-28 Days],
sum(case when a.Days BETWEEN 29 AND 84 THEN 1 ELSE 0 END) [29-84 Days],
sum(case when a.Days BETWEEN 85 AND 182 THEN 1 ELSE 0 END) [85-182 Days],
sum(case when a.Days >= 183 THEN 1 ELSE 0 END) [183+],
sum(case when ModifiedOn is null then 1 else 0 end) [NullRows],
count(*) as [RowCount]
From
(
Select DATEDIFF(dd, ModifiedOn, getdate()) AS [Days],
ModifiedOn
From MSCRM_REPORTING.dbo.apuk_erqanswerBase
) a
You can try this as well:
Select N'MSCRM_REPORTING' As [Database],
N'dbo' As [Schema],
N'apuk_erqanswerBase' As [Table],
N'ModifiedOn' As ChangeType,
sum(case when DATEDIFF(dd, ModifiedOn, getdate()) BETWEEN 0 AND 7 THEN 1 ELSE 0 END) [0-7 Days],
sum(case when DATEDIFF(dd, ModifiedOn, getdate()) BETWEEN 8 AND 28 THEN 1 ELSE 0 END) [8-28 Days],
sum(case when DATEDIFF(dd, ModifiedOn, getdate()) BETWEEN 29 AND 84 THEN 1 ELSE 0 END) [29-84 Days],
---------------------
from MSCRM_REPORTING.dbo.apuk_erqanswerBase

Can somebody help me translate CASE statement with dates?

I need to modify a Stored Procedure, and I cant understand how day manipulate those dates in a WHERE clause. Especially when END=1. I have never see that before.
CASE WHEN #DateFrom IS NULL THEN 1 ELSE
CASE WHEN INV.InvoiceDate > INV.EffectiveDate THEN
CASE WHEN dateDiff(d, #DateFrom, INV.InvoiceDate) >= 0
AND dateDiff(d, #DateTo, INV.InvoiceDate) <= 0 Then 1 else 0 end
ELSE
CASE WHEN dateDiff(d, #DateFrom, INV.EffectiveDate) >= 0
AND dateDiff(d, #DateTo, INV.EffectiveDate) <= 0 Then 1 else 0 end
END
END = 1
when you convert it into single case it seems easier to understand:
CASE
WHEN #DateFrom IS NULL THEN 1
WHEN #DateFrom IS NOT NULL AND dateDiff(d, #DateFrom, INV.InvoiceDate) >= 0 AND dateDiff(d, #DateTo, INV.InvoiceDate) <= 0 THEN 1
ELSE 0 END =1
you could also try this
CASE
WHEN #DateFrom IS NULL THEN 1 ELSE
(CASE
WHEN dateDiff(d, #DateFrom, INV.InvoiceDate) >= 0 AND dateDiff(d, #DateTo, INV.InvoiceDate) <= 0 THEN 1 ELSE 0
END)
END)
END = 1
what i'm getting at is the second level of this case is weird. the when and else cases are the same, so it doesn't need to be there.
(CASE
WHEN INV.InvoiceDate > INV.EffectiveDate
THEN (CASE
WHEN dateDiff(d, #DateFrom, INV.InvoiceDate) >= 0 AND dateDiff(d, #DateTo, INV.InvoiceDate) <= 0 THEN 1 ELSE 0
END)
ELSE (CASE
WHEN dateDiff(d, #DateFrom, INV.EffectiveDate) >= 0 AND dateDiff(d, #DateTo, INV.EffectiveDate) <= 0 THEN 1 ELSE 0
END)
This one is gives an error. I think parenthesis is missing somewhere
CASE
WHEN #DateFrom IS NULL THEN 1 ELSE
(CASE
WHEN dateDiff(d, #DateFrom, INV.InvoiceDate) >= 0 AND dateDiff(d, #DateTo, INV.InvoiceDate) <= 0 THEN 1 ELSE 0
END)
END)
END = 1

SQL- Date Diff- # of week in each month between two date periods

Problem: Display in columns the number of weeks in each month between two date periods (out to three months is fine for now). If possible, from the current day (Dynamic)
Where I currently am:
SELECT Q3.[Begin Date]
,Q3.[End Date]
,Q3.Diff_in_Year
,sum(CASE
WHEN Q3.Year_Counter = 0
THEN datediff(mm, Q3.y_start, Q3.y_end) + 1
ELSE 0
END) Y1
,sum(CASE
WHEN Q3.Year_Counter = 1
THEN datediff(mm, Q3.y_start, Q3.y_end) + 1
ELSE 0
END) Y2
,sum(CASE
WHEN Q3.Year_Counter = 2
THEN datediff(mm, Q3.y_start, Q3.y_end) + 1
ELSE 0
END) Y3
,sum(CASE
WHEN Q3.Year_Counter = 3
THEN datediff(mm, Q3.y_start, Q3.y_end) + 1
ELSE 0
END) Y4
,sum(CASE
WHEN Q3.Year_Counter = 4
THEN datediff(mm, Q3.y_start, Q3.y_end) + 1
ELSE 0
END) Y5
,sum(CASE
WHEN Q3.Year_Counter = 5
THEN datediff(mm, Q3.y_start, Q3.y_end) + 1
ELSE 0
END) Y6
,sum(CASE
WHEN Q3.Year_Counter = 6
THEN datediff(mm, Q3.y_start, Q3.y_end) + 1
ELSE 0
END) Y7
,sum(CASE
WHEN Q3.Year_Counter = 7
THEN datediff(mm, Q3.y_start, Q3.y_end) + 1
ELSE 0
END) Y8
,sum(CASE
WHEN Q3.Year_Counter = 8
THEN datediff(mm, Q3.y_start, Q3.y_end) + 1
ELSE 0
END) Y9
,sum(CASE
WHEN Q3.Year_Counter = 9
THEN datediff(mm, Q3.y_start, Q3.y_end) + 1
ELSE 0
END) Y10
FROM (
SELECT Q1.[Begin Date]
,Q1.[End Date]
,Q1.years Diff_in_Year
,Q2.number AS Year_Counter
,(
CASE
WHEN Q2.number = 0
THEN Q1.[Begin Date]
ELSE dateadd(yy, datediff(yy, 0, dateadd(yy, q2.number, q1.[Begin Date])), 0)
END
) AS y_Start
,(
CASE
WHEN ((Q1.years - 1) = Q2.number)
THEN Q1.[End Date]
ELSE DATEADD(yy, DATEDIFF(yy, 0, dateadd(yy, q2.number + 1, q1.[Begin Date]) + 1), - 1)
END
) AS y_End
,Year(Q1.[Begin Date]) + Q2.number YearInYYYY
FROM (
SELECT [Begin Date]
,[End Date]
,DATEDIFF(year, [Begin Date], [End Date]) + 1 AS years
FROM my dates
) Q1
INNER JOIN master..spt_values Q2 ON Q2.type = 'P'
AND Q2.number < Q1.years
) Q3
GROUP BY Q3.[Begin Date]
,Q3.[End Date]
,q3.Diff_in_Year
How the current code works: Given a date range, the number of months in each year between two dates. IE 1/1/2014 - 1/18/2015 would give two columns "2014" and 2015" the value of 2014 is 12 and the value of 2015 is 1 signifying that there are 13 months between the specified dates.
What I am hoping to achieve is something similar to
Start Date End Date Month 1 Month 2 Month 3
-----------------------------------------------------
1/1/2014 3/8/2014 4 4 1
Dynamic SQL solutions aside (search for dynamic pivot in TSQL), I whipped up a couple of answers. Since your question is unclear whether you want weeks or months, I put together a quick one for each.
Months Example Here:
declare #startdate date = '1/1/2014', #enddate date = '3/1/2015'
select p.*
from (
select #startdate as StartDate, #enddate as EndDate, right(convert(varchar,(dateadd(mm,RowID-1,#startdate)),105),4) [Group]
from (
select *, row_number()over(order by name) as RowID
from master..spt_values
) d
where d.RowID <= datediff(mm, #startdate, #enddate)
) t
pivot (
count([Group]) for [Group] in (
[2014],[2015]
)
) p
Weeks Example Here:
declare #startdate date = '1/1/2014', #enddate date = '3/1/2015'
select p.*
from (
select #startdate as StartDate, #enddate as EndDate, right(convert(varchar,(dateadd(ww,RowID-1,#startdate)),105),7) [Group]
from (
select *, row_number()over(order by name) as RowID
from master..spt_values
) d
where d.RowID <= datediff(ww, #startdate, #enddate)
) t
pivot (
count([Group]) for [Group] in (
[01-2014]
, [02-2014]
, [03-2014]
, [04-2014]
, [05-2014]
, [06-2014]
, [07-2014]
, [08-2014]
, [09-2014]
, [10-2014]
, [11-2014]
, [12-2014]
, [01-2015]
, [02-2015]
, [03-2015]
)
) p