sql - 查询每小时数据报表

标签 sql sql-server

我的任务是制作一份报告,该报告将显示一个条形图,其中 X 轴是轮类时间,因此底部是 1-8。条形是每小时完成的交易数量。因此,条形图可以轻松地让您看到,在第一个小时我们处理了 30 个订单,第二个小时我们处理了 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

此外,这位于报表调用的存储过程中。

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

最佳答案

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)

关于sql - 查询每小时数据报表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17108766/

相关文章:

sql-server - SQL Server返回与值不等于<>和NULL的行

php - 这个 SQL 查询是安全的吗?

Mysql生成简单存储函数

c# - 带有 Entity Framework 6 的 "Case statement"中的 "group by query"

c# - 如何使用 C#、ASP.NET、SQL Server 端处理实现 jQuery DataTables 插件?

SQL Server 2008,加入还是不加入?

sql - 如何计算最终总和并计算百分比

mysql - 从父值计算子成员

php - 错误 : You have an error in your SQL syntax; check the manual that corresponds to your MySQL

sql-server - SQL Server 使用 Case When 和常量的语法进行排序