查询每小时报告的数据

时间:2013-06-14 12:44:50

标签: sql sql-server

我的任务是报告显示一个条形图,其中X轴是班次的小时数,因此沿着底部1-8。条形码是每小时完成的交易数量。所以条形图很容易让你看到我们在第一个小时处理了30个订单,小时2我们处理了25个,依此类推,直到轮班结束。

我无法弄清楚如何实际创建此报告。我唯一的选择是做这样的事情(理解这只是伪代码,不要在语法问题上发表评论):

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

此外,这是在报告调用的存储过程中。

有更好的方法吗?我是否应该将整天的数据发送到报告中并以某种方式处理它?任何见解都将不胜感激。

1 个答案:

答案 0 :(得分: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() here

您当然可以为日,周,任何您想要的内容添加更多分组:

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)