I’m trying to write a Microsoft SQL Server 2005 query that counts a total value, grouped by date with a cut-off point of 10:00am ?
eg: Table Orders
DateReceived Total
01-01-2012 06:10:01 2
01-01-2012 08:10:01 2
01-01-2012 10:10:01 4
02-01-2012 08:00:07 4
02-01-2012 10:00:07 4
I’d like to count the daily total, using 10:00 am as the cut-off point, so any orders before 10:00am appear in the total for the day before, and after 10:00 am in the total for that day.
I’m hoping to see query results like:
DateReceived Total
31-12-2011 4
01-01-2012 8
02-01-2012 4
I know how to group by just the date in Microsoft SQL Server:
SELECT DISTINCT CONVERT(varchar, [DateReceived], 111) AS [dt_DateReceived],
SUM([Total]) AS perday
FROM [Orders]
GROUP BY CONVERT(varchar, [DateReceived], 111)
ORDER BY [DateReceived] DESC
However I am unsure how to add a cut off time of 10:00am using Microsoft SQL Server.
Using MySQL, I can achieve this by grouping on a subtracted interval, however am unsure how to translate this to SQL Server:
GROUP BY
DATE(DATE_SUB( DateReceived , INTERVAL 10 HOUR))
Could anyone advise?
Thank you,
Jack
See the translation:
Test script
Note that my local datetime format is yyyy-mm-dd
The testscript can be executed here
PS: Distinction is not needed