sql - 如何在 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制作,但它可能已经存在了。
解决方案
您可以使用聚合。我在想:
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;
推荐阅读
- c# - 消费者的 CQRS 预测不是为 API 组合架构设计的吗?
- sql-server - 它是否需要另一个在 where 子句中有一些额外的列
- javascript - 如何在 angularjs onclick of button 中调用 alt + f4 键
- c# - Azure Function BlobTrigger 不捕获所有传入事件
- firebase - 有没有办法在不登录的情况下获得firebase Auth UID?
- angular - 如何重置 ngx-treeview
- api - 微服务架构中的 API 调用
- java - Flink:从行字段中提取数组
- java - 有没有办法按行拆分 RDD?
- javascript - JavaScript onclick 多 div 更改类列表添加/删除返回到后面?