按星期几组

时间:2016-08-17 15:16:55

标签: sql postgresql

我有一个conversations列inserted_at

我想绘制一张图表,显示随时间创建的conversations的数量。

我希望能够按日期,星期几和日期来分组数据,以显示可能的趋势。

我将使用7天,1个月和6个月的间隔。

示例:

时间间隔1 month分组day of week

我想要像

这样的东西
| Monday | Tuesday | Wednesday | Thursday | Friday |
|--------|---------|-----------|----------|--------|
| 11     | 22      | 19        | 17       | 10     |

或间隔:7 days分组date

| 1/1 | 2/1 | 3/1 | 4/1 | 5/1 | 6/1 | 7/1 |
|-----|-----|-----|-----|-----|-----|-----|
| 11  | 22  | 19  | 17  | 10  | 10  | 7   |

实现此目的的最佳方法是什么(非常感谢示例),PostgreSQL是否适合这类查询?

最后,是否有任何特殊类型的索引可以改善此类查询?

2 个答案:

答案 0 :(得分:5)

一周中的几天:

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 nullnull,因此只会计算true

在较新的版本中,有一个聚合filter

count(*) filter (where extract(dow from inserted_at) = 4) as thursday

答案 1 :(得分:2)

一个简单的group by可以解决这个问题:

select 
  extract(dow from inserted_at)
  , count(*)
from conversations
where inserted_at between date '2016-08-08' and '2016-08-08' + interval '7 days'
group by 1;

该查询的改进版本(以确保包含计数0的天数):

with week as
(
   SELECT s.d day FROM generate_series(1,7) s(d)
)
select
  week.day
  , count(extract(dow from c.inserted_at))
from days 
left join conversations c on week.day = extract(dow from c.inserted_at)
     and c.inserted_at between now() and now() + interval '7 days'
group by week.day
order by week.day;

inserted_at列上的索引有助于快速选择相关间隔。