I recently wrote a post about Find the WeekEnds in this Quarter or Year using SQL Server 2005/2008 . For the same report, a requirement was to pull the working days in the current Quarter and number them sequentially. The requirement also stated that the weekends should be numbered as 0 in the report. Here’s how the query works for this requirement
DECLARE @date1 datetime
DECLARE @date2 datetime
SELECT @date1 = DATEADD(qq,DATEDIFF(qq,0,GETDATE()),0)
SELECT @date2= DATEADD(qq,DATEDIFF(qq,-1,GETDATE()),-1);
WITH CTE (dt)
AS
(
SELECT @date1
UNION ALL
SELECT DATEADD(d,1,dt) FROM CTE
WHERE dt < @date2
)
SELECT cte.dt as BDate, COALESCE (dte.WorkingDay,'') as DayNumber from CTE cte
LEFT JOIN
(
SELECT dt as d,
ROW_NUMBER() OVER (PARTITION BY DATEDIFF(mm, '19000101', dt) ORDER BY dt) WorkingDay
FROM CTE
WHERE DATENAME(dw,dt) Not In ('Saturday', 'Sunday')
)
AS dte ON dte.d = cte.dt
ORDER BY cte.dt
OUTPUT
2 comments:
Excellent Blog!
Shouldn't that be:
PARTITION BY DATEDIFF(qq,19000101', dt)
?
Post a Comment