Why Experts Exchange?

Experts Exchange always has the answer, or at the least points me in the correct direction! It is like having another employee that is extremely experienced.

Jim Murphy
Programmer at Smart IT Solutions

When asked, what has been your best career decision?

Deciding to stick with EE.

Mohamed Asif
Technical Department Head

Being involved with EE helped me to grow personally and professionally.

Carl Webster
CTP, Sr Infrastructure Consultant
Ask ANY Question

Connect with Certified Experts to gain insight and support on specific technology challenges including:

Professional Opinions
Ask a Question
Did You Know?

We've partnered with two important charities to provide clean water and computer science education to those who need it most. READ MORE

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 Comments1 Solution560 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
Avatar of arugula

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

This problem has been solved!
Unlock 1 Answer and 7 Comments.
See Answers