我的问题是我正在运行一个查询,有时会出现一组空结果(没有返回任何内容)。我需要修改输出,以便仍然用适当的“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 |
关于如何实现这一目标有什么建议吗?
最佳答案
据我所知,没有什么简单的方法可以做到这一点,但它是可以实现的。以下查询将打印与 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;
关于mysql - 转换查询以处理空集结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33768874/