2

I've been tasked with a report that will show a bar chart where the X-axis is the hours of the shift, so 1-8 along the bottom. The bars are the number of transactions accomplished per hour. So the bar chart would easily let you see that in the first hour we've processed 30 orders, hour 2 we've processed 25, and so on, to the end of the shift.

I'm having trouble figuring out how to actually create this report though. Is my only option to do something like this (understand this is just pseudo-code, don't bother commenting on syntax issues):

create table #temp
(
  Hour int,
  Units int
)

insert into #temp
SELECT 1 as Hour, sum(Units) Units
FROM orders
WHERE DateCreated >= '6/14/2013 08:00:00' AND DateCreated < '6/14/2013 09:00:00'

insert into #temp
SELECT 2 as Hour, sum(Units) Units
FROM orders
WHERE DateCreated >= '6/14/2013 09:00:00' AND DateCreated < '6/14/2013 10:00:00'

insert into #temp
SELECT 3 as Hour, sum(Units) Units
FROM orders
WHERE DateCreated >= '6/14/2013 11:00:00' AND DateCreated < '6/14/2013 12:00:00'

.. and so on ..

select * from #temp

Also, this is in a stored procedure that the report calls.

Is there a better way to do this? Should I be just sending the entire day's data to the report and somehow handling it there? Any insights would be appreciated.

4

1 回答 1

5
SELECT DATEPART(hh, DateCreated) AS hour, sum(Units) Units
FROM orders
WHERE DateCreated >= '6/14/2013' AND DateCreated < '6/15/2013'
GROUP BY DATEPART(hh, DateCreated)

阅读更多关于DATEPART() 这里

当然,您可以根据需要为日、周添加更多分组:

SELECT DATEPART(dd, DateCreated) AS day, DATEPART(hh, DateCreated) AS hour, sum(Units) Units
FROM orders
WHERE DateCreated >= '6/10/2013' AND DateCreated < '6/15/2013'
GROUP BY DATEPART(dd, DateCreated), DATEPART(hour, DateCreated)
于 2013-06-14T12:48:43.030 回答