I want to calculate total say Sundays,Mondays...Saturdays
between two days. I want a do it in a select query because that is mandatory according to the situation where I'm currently working.
I have some working code where I'm able to calculate all sundays but not working in case of mondays
DECLARE @StartDate DATE = '2011-10-01',
@EndDate DATE = '2011-10-31'
SELECT DayCount = count(* )
FROM (SELECT TOP ( datediff(DAY,@StartDate,@EndDate) + 1 )
[Date] = dateadd(DAY,ROW_NUMBER()
OVER(ORDER BY c1.name),
DATEADD(DD,-1,@StartDate))
FROM [master].[dbo].[spt_values] c1 ) x
WHERE datepart(dw,[Date]) = 1;
I think your query delivers the correct result but could be simplified a bit.
It is however dependent on SET DATEFIRST setting.
datepart(dw,[Date]) = 1
will count the number of Mondays ifSET DATEFIRST
is 1.Try this:
Result:
Update: Another query that does the same.
Calculating a simple number of particular days between two dates should NOT require a numbers table. Forcing I/O into a simple date calculation is not good practice.
You can do a simple calculation by figuring out the number of weeks between the two dates, and adjusting for where the desired day falls in relation to the end periods.
But I want to present another way to do it that actually allows you to specify any pattern of days you want to count. For example, it is just as easy to calculate the number of Saturdays and Sundays at once as it is to calculate the number of Mondays. I took pains to also make this query entirely independent of the
SET DATEFIRST
setting.The trick is the string inside of the
Replicate
function. It encodes Monday by placing a1
in the second position (starting with Sunday as the first day).You may feel repelled by such a string-munching solution as this--but I have played with this before and expect that you will find it very difficult to improve on its speed with regular date math (especially the part about being able to calculate for multiple days at once).