我有一个表 conversations
,其中有一个 inserted_at
列
我想绘制一个图表来显示随着时间的推移创建的对话
的数量。
我希望能够按日期、星期几和日期时间对数据进行分组,以显示可能的趋势。
我将使用 7 天、1 个月和 6 个月的间隔。
例子:
间隔:1 个月
按星期几
分组
我想要这样的东西
| Monday | Tuesday | Wednesday | Thursday | Friday |
|--------|---------|-----------|----------|--------|
| 11 | 22 | 19 | 17 | 10 |
或间隔:7 天
按日期
分组
| 1/1 | 2/1 | 3/1 | 4/1 | 5/1 | 6/1 | 7/1 |
|-----|-----|-----|-----|-----|-----|-----|
| 11 | 22 | 19 | 17 | 10 | 10 | 7 |
完成此任务的最佳方法是什么(示例将不胜感激),PostgreSQL 是否适合此类查询?
最后,是否有任何特殊类型的索引可以改进此类查询?
最佳答案
星期几:
select
count(extract(dow from inserted_at) = 1 or null) as monday,
count(extract(dow from inserted_at) = 2 or null) as tuesday,
count(extract(dow from inserted_at) = 3 or null) as wednesday,
count(extract(dow from inserted_at) = 4 or null) as thursday,
count(extract(dow from inserted_at) = 5 or null) as friday,
from conversations
count
只计算 not null
值。 false or null
是 null
所以只有 true
会被计算在内。
在较新的版本中有一个聚合过滤器
:
count(*) filter (where extract(dow from inserted_at) = 4) as thursday
关于sql - 按星期几分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39000498/