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>