首页 > 解决方案 > 如何在 PostgreSQL 中获取按 x 轴按月和 y 轴按小时分组的计数表?

问题描述

有一个包含很多事件的日志表,我想知道什么是统计数据,即每个月的什么时间发生了多少事件。

Data sample:
 date_create         | event
---------------------+---------------------------
 2018-03-01 18:00:00 | Something happened
 2018-03-05 18:15:00 | Something else happened
 2018-03-06 19:00:00 | Something happened again
 2018-04-01 18:00:00 | and again

结果应如下所示:

 hour | 03 | 04
------+----+----
 18   |  2 |  1
 19   |  1 |  0

我可以用 CTE 完成它,但每次都需要大量的手动工作。我的猜测是它可以用funciton制作,但它可能已经存在了。

标签: sqlpostgresql

解决方案


您可以使用聚合。我在想:

select extract(hour from date_create) as hh,
       sum(case when extract(month from date_create) = 3 then 1 else 0 end) as month_03,
       sum(case when extract(month from date_create) = 4 then 1 else 0 end) as month_04
from t
group by hh
order by hh;

推荐阅读