Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2000 Forums
 SQL Server Development (2000)
 Grouping by date range

Author  Topic 

AskSQLTeam
Ask SQLTeam Question

0 Posts

Posted - 2002-02-19 : 09:00:28
Sarah writes "Hi! I have a question for SQL Server 2000.

Say I have a table of orders and the date of the order. I would like to run a query that will tell me how many orders there were today, yesterday, this week, last week, this month, last month, etc., etc. like this:


Range Orders
---------- -----------
yesterday 1
this week 1
last week 2
this month 4
last month 8
this year 12
last year 40
total 52

I was able to do this with a union of several queries:


select case datediff(day,orderdate, GETDATE())
when 0 then 'today' when 1 then 'yesterday' end as Range,
count(resultid) as Orders from tblOrders
group by datediff(day,orderdate, GETDATE())
having datediff(day,orderdate, GETDATE()) in (0,1)
union
select case datediff(week,orderdate, GETDATE())
when 0 then 'this week' when 1 then 'last week' end as Range,
count(resultid) as Orders from tblOrders
group by datediff(week,orderdate, GETDATE())
having datediff(week,orderdate, GETDATE()) in (0,1)
union
select case datediff(month,orderdate, GETDATE())
when 0 then 'this month' when 1 then 'last month' end as Range,
count(resultid) as Orders from tblOrders
group by datediff(month,orderdate, GETDATE())
having datediff(month,orderdate, GETDATE()) in (0,1)
union
select case datediff(year,orderdate, GETDATE())
when 0 then 'this year' when 1 then 'last year' end as Range,
count(resultid) as Orders from tblOrders
group by datediff(year,orderdate, GETDATE())
having datediff(year,orderdate, GETDATE()) in (0,1)
union
select 'total' as Range, count(resultid) as Orders
from tblOrders

I'm really curious if it's possible to get the same results with just one query. This might be similar to this question, but it would have to group by different datediffs.

PS. A big plus would be if the query could also return that there were 0 orders in a daterange. "

   

- Advertisement -