我有一个conversations带有inserted_at列的表
我想绘制一个图表,显示conversations随时间创建的数量.
我希望能够按日期,星期几和日期时间对数据进行分组,以显示可能的趋势.
我将使用7天,1个月和6个月的间隔.
例:
间隔:1 month分组day of week
我喜欢类似的东西
| Monday | Tuesday | Wednesday | Thursday | Friday |
|--------|---------|-----------|----------|--------|
| 11 | 22 | 19 | 17 | 10 |
Run Code Online (Sandbox Code Playgroud)
或间隔:7 days分组依据date
| 1/1 | 2/1 | 3/1 | 4/1 | 5/1 | 6/1 | 7/1 |
|-----|-----|-----|-----|-----|-----|-----|
| 11 | 22 | 19 | 17 | 10 | 10 | 7 |
Run Code Online (Sandbox Code Playgroud)
实现这一目标的最佳方法是什么(非常感谢示例),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
Run Code Online (Sandbox Code Playgroud)
count只计算not null值.false or null是null这样只会true被计算在内.
在较新的版本中有一个聚合filter:
count(*) filter (where extract(dow from inserted_at) = 4) as thursday
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2642 次 |
| 最近记录: |