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 1this week 1last week 2this month 4last month 8this year 12last year 40total 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)unionselect 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)unionselect 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)unionselect 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)unionselect '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. "