Oracle 11 查询 group/count 并按小时拆分结果

Oracle 11 query group/count and split result by hour

我在 Oracle v11 上有一个简单的查询来对记录进行分组和计数,没什么特别的:

select ADDR, count(ADDR) from DBTB group by ADDR;

rable 也有 TIMESTAMP 列,我想做的是按小时分组和计算唯一的 ADDR。 例如在 table:

TIMESTAMP               ADDR
19-OCT-2021 17:15:00    12345
19-OCT-2021 17:20:00    12345
19-OCT-2021 17:25:00    12345
19-OCT-2021 17:27:00    67890
19-OCT-2021 18:10:00    55555
19-OCT-2021 18:20:00    55555
19-OCT-2021 18:30:00    66666
19-OCT-2021 18:43:00    77777

输出应该是:

HOUR  COUNT
17        2
18        3

有人可以帮我做一个查询来计算和分组按小时划分的相同 ADDR 吗? 谢谢 卢卡斯

使用TO_CHAR()获取每个时间戳的小时数:

SELECT TO_CHAR("TIMESTAMP", 'HH24') HOUR,
       COUNT(DISTINCT "ADDR") COUNT
FROM DBTB
GROUP BY TO_CHAR("TIMESTAMP", 'HH24');

可能你还需要按日期分组:

SELECT TRUNC("TIMESTAMP") DAY,
       TO_CHAR("TIMESTAMP", 'HH24') HOUR,
       COUNT(DISTINCT "ADDR") COUNT
FROM DBTB
GROUP BY TRUNC("TIMESTAMP"), TO_CHAR("TIMESTAMP", 'HH24');

或筛选特定日期:

SELECT TO_CHAR("TIMESTAMP", 'HH24') HOUR,
       COUNT(DISTINCT "ADDR") COUNT
FROM DBTB
WHERE TRUNC("TIMESTAMP") = TO_DATE('19-Oct-2021', 'DD-MON-YYYY')
GROUP BY TO_CHAR("TIMESTAMP", 'HH24');

参见demo