T-SQL: How do you group by daily date? What is the design pattern/best practice?
I occasionally need to generate a report using SQL that rolls up values by date of month... say the last 30 days or last 60 days, etc., of some data.
What is the query design pattern for this?
The code below works but seems too complicated. It groups by the number of calendary days since 2007, then later "re-constitutes" the date by adding water (er, calling DateAdd).
A colleague also mentioned grouping by Floor(Cast(MyDateField as float)) but that still seems indirect.
Does Microsoft have a nice solution for this?
Does everyone have to do this funny stuff just to generate a report by date?
select DateAdd(day,Days2007,'1-1-2007'),CNT from ( select datediff(day, '1-1-2007', MyDateField) as Days2007, count(PKField) as CNT from MyTable group by datediff(day, '1-1-2007', MyDateField)) subQueryAliasorder by Days2007 desc
Open in new window