答案 0 :(得分:0)
创建一个包含数小时的表格可能对您有价值:
create table hours (hr int primary key);
insert into hours values
(1),(2),(3),(4),(5),(6),(7),(8),(9),(10),(11),(12),
(13),(14),(15),(16),(17),(18),(19),(20),(21),(22),(23),(24);
让我们假设你的表在 MySQL :
中看起来像这样create table test (
sale_no int auto_increment primary key,
entry_date timestamp,
sales_done int
);
或者如果它是 SQL Server :
create table test (
sale_no int identity primary key,
entry_date datetime,
sales_done int
);
数据如下所示:
insert into test (entry_date, sales_done) values
('2017-03-06 01:27:00', 5), ('2017-03-06 01:26:00', 7),
('2017-03-06 02:25:00', 7), ('2017-03-06 02:23:00', 6),
('2017-03-06 02:18:00', 5), ('2017-03-06 02:07:00', 4),
('2017-03-06 03:26:00', 5), ('2017-03-06 03:25:00', 7),
('2017-03-06 04:23:00', 7), ('2017-03-06 04:18:00', 8);
查询您在MySQL中的写作是:
select h.hr, coalesce(t.count, 0) as count
from hours h
left join (
select hour(entry_date) as hr, sum(sales_done) as count
from test
group by hour(entry_date)
) t on t.hr = h.hr
order by h.hr;
查询您是否在SQL Server中编写:
select h.hr, coalesce(t.count, 0) as count
from hours h
left join (
select datepart(hour, entry_date) as hr, sum(sales_done) as count
from test
group by datepart(hour, entry_date)
) t on t.hr = h.hr
order by h.hr;
<强>结果:强>
+----+-------+
| hr | count |
+----+-------+
| 1 | 12 |
| 2 | 22 |
| 3 | 12 |
| 4 | 15 |
| 5 | 0 |
| .. | .. |
| 24 | 0 |
+----+-------+
MySQL示例:http://sqlfiddle.com/#!9/943db3/1
SQL Server示例:http://rextester.com/QQK91065