根据日期时间获取类别的最大计数值

Get max count value of category based on date time

我有一个 table 看起来像这样:

datetime category
2021.31.01 12:12:00 X
2021.31.01 12:23:00 X
2021.31.01 15:01:00 X
2021.31.01 15:23:00 X
2021.31.01 15:37:00 X
2021.30.02 11:23:00 Y
2021.30.02 15:13:00 X

需要的是获取按日期和小时分组的每种类型的最大计数值。

所以,最终结果应该是这样的:

category date_hour number_of_occurances
X 2021.31.01 15:00:00 3
Y 2021.30.02 11:00:00 1

查询现在的样子:

SELECT
    category,
    to_timestamp(datetime, 'y-M-d H') as date_hour,
    COUNT(*) AS number_of_occurances
FROM <my_table>
GROUP BY category, date_hour
ORDER BY number_of_occurances DESC

使用 window 函数查找每个类别的最高计数,然后只显示排名第一的 category/hours。

SELECT category, date_hour, number_of_occurances
FROM
(
  SELECT
    category,
    TRUNC(datetime, 'HH24') AS date_hour,
    COUNT(*) AS number_of_occurances,
    RANK() OVER (PARTITION BY category ORDER BY COUNT(*) DESC) AS rnk
  FROM <my_table>
  GROUP BY category, TRUNC(datetime, 'HH24')
) ranked
WHERE rnk = 1
ORDER BY category;