我的问题是我正在运行一个查询,其中有时会有一组空的结果(没有返回任何内容)。我需要修改输出,以便没有数据的小时数仍然用适当的“0”计数表示。以下文档列出了我正在使用的查询以及示例输出。
正在使用的当前查询:
select date(look) as "Day",concat(date_format(look, '%H'),':00') as "Hour", count(distinct(session_name)) as "Count"
from db.login_stats
where look > '2015-10-06'
group by date(look),concat(date_format(look, '%H'),':00');
当前输出:
+------------+-------+-------+
| Day | Hour | Count |
+------------+-------+-------+
| 2015-10-07 | 09:00 | 1 |
| 2015-10-07 | 10:00 | 1 |
| 2015-10-07 | 11:00 | 1 |
| 2015-10-07 | 12:00 | 2 |
| 2015-10-07 | 13:00 | 2 |
| 2015-10-07 | 14:00 | 2 |
| 2015-10-07 | 15:00 | 1 |
| 2015-10-07 | 18:00 | 1 |
我希望输出能够重新安装:
+------------+-------+-------+
| Day | Hour | Count |
+------------+-------+-------+
| 2015-10-07 | 00:00 | 0 |
| 2015-10-07 | 01:00 | 0 |
| 2015-10-07 | 02:00 | 0 |
| 2015-10-07 | 03:00 | 0 |
| 2015-10-07 | 04:00 | 0 |
| 2015-10-07 | 05:00 | 0 |
| 2015-10-07 | 06:00 | 0 |
| 2015-10-07 | 07:00 | 0 |
| 2015-10-07 | 08:00 | 0 |
| 2015-10-07 | 09:00 | 1 |
| 2015-10-07 | 10:00 | 1 |
| 2015-10-07 | 11:00 | 1 |
| 2015-10-07 | 12:00 | 2 |
| 2015-10-07 | 13:00 | 2 |
| 2015-10-07 | 14:00 | 2 |
| 2015-10-07 | 15:00 | 1 |
| 2015-10-07 | 16:00 | 0 |
| 2015-10-07 | 17:00 | 0 |
| 2015-10-07 | 18:00 | 1 |
| 2015-10-07 | 19:00 | 0 |
| 2015-10-07 | 20:00 | 0 |
| 2015-10-07 | 21:00 | 0 |
| 2015-10-07 | 22:00 | 0 |
| 2015-10-07 | 23:00 | 0 |
有关如何完成此任务的任何建议?
答案 0 :(得分:1)
我所知道的那种方法并非无关紧要,但它是可以实现的。以下查询将打印与WHERE子句匹配的每一天的所有24小时(例如,它将打印当前数据的所需输出,如果插入look
等于2015-10-08
的额外行它会在输出中再添加24行:
-- populate a table with 24 rows, one per hour
create table hours(hour time);
insert into hours values(0), (10000), (20000);
insert into hours select hour + 30000 from hours;
insert into hours select hour + 60000 from hours;
insert into hours select hour + 120000 from hours;
-- now this query will do what you want
select dates.d as "Day",dates.h as "Hour", count(distinct(session_name)) as "Count"
from db.login_stats RIGHT JOIN
(
SELECT date(look) as d, concat(date_format(hour, '%H'),':00') as h
FROM login_stats CROSS JOIN hours
WHERE date(look) > '2015-10-06' -- moved your WHERE here
GROUP BY 1, 2
ORDER BY 1, 2
) dates
ON date(look) = d AND concat(date_format(look, '%H'),':00') = h
group by dates.d, dates.h;