troubleshooting Question

T-SQL: How do you group by daily date? What is the design pattern/best practice?

Avatar of ZuZuPetals
ZuZuPetalsFlag for United States of America asked on
Microsoft SQL Server
7 Comments3 Solutions560 ViewsLast Modified:
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)
) subQueryAlias
order by Days2007 desc

Our community of experts have been thoroughly vetted for their expertise and industry experience.

Join our community to see this answer!
Unlock 3 Answers and 7 Comments.
Start Free Trial
Learn from the best

Network and collaborate with thousands of CTOs, CISOs, and IT Pros rooting for you and your success.

Andrew Hancock - VMware vExpert
See if this solution works for you by signing up for a 7 day free trial.
Unlock 3 Answers and 7 Comments.
Try for 7 days

”The time we save is the biggest benefit of E-E to our team. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange.

-Mike Kapnisakis, Warner Bros