oracle - Oracle SQL 按小时分组 24 小时
问题描述
我有这个查询,它有效:
SELECT TO_CHAR(last_date_called,'HH24'), count(*)
FROM log_table
GROUP BY TO_CHAR(last_date_called,'HH24');
但是,在某些情况下,没有 24 小时的数据。我想要做的是始终生成 24 行,如果那个小时没有任何内容,则返回 0。因此,结果可能如下所示:
00 10
01 25
02 33
03 0
04 55
05 0
06 23
等等........
解决方案
您需要一个行生成器来创建一天中的所有时间,然后将其外部连接到您的“真实”表中。像这样的东西(见代码中的注释):
SQL> with
2 hours as
3 -- row generator, to create all hours in a day
4 (select lpad(level - 1, 2, '0') hour
5 from dual
6 connect by level <= 24
7 ),
8 log_table (last_date_called) as
9 -- sample data, just to return "something"
10 (select to_date('08.07.2021 13:32', 'dd.mm.yyyy hh24:mi') from dual union all
11 select to_date('16.02.2021 08:20', 'dd.mm.yyyy hh24:mi') from dual
12 )
13 -- final query
14 select h.hour,
15 count(l.last_date_called) cnt
16 from hours h left join log_table l on h.hour = to_char(l.last_date_called, 'hh24')
17 group by h.hour
18 order by h.hour;
HO CNT
-- ----------
00 0
01 0
02 0
03 0
04 0
05 0
06 0
07 0
08 1
09 0
10 0
11 0
12 0
13 1
14 0
15 0
16 0
17 0
18 0
19 0
20 0
21 0
22 0
23 0
24 rows selected.
SQL>
推荐阅读
- design-patterns - 外观设计模式是否也只涉及类/模块或实际的 API 调用?
- opencv - 保存时图像为黑色,但打印时正常
- python - 访问嵌套字典中的更深层次的列表项?
- continuous-integration - 为什么外部 git 存储库不是 Azure 门户中部署中心的选项?
- swift - Swift 泛型:使用泛型类型的属性扩展非泛型类型,其中泛型参数是扩展类型
- jekyll - 更改博客文章的 Jekyll URL
- matlab - 如何删除极坐标图上的 theta 网格和半径网格?
- html - 3个下拉单独的下拉列表,只选择最上面的一个
- asp.net - 如果没有结果,Gridview 就会消失
- javascript - 使用按字母顺序排序的选项填充选择