繁体   English   中英

按星期几组

[英]Group by day of week

我有一个与inserted_at列的表conversations

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

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

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

例:

间隔: day of week 1 month

我喜欢类似的东西

| Monday | Tuesday | Wednesday | Thursday | Friday |
|--------|---------|-----------|----------|--------|
| 11     | 22      | 19        | 17       | 10     |

或间隔:按date分组7 days

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

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

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

一个简单的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列上的索引将有助于快速选择相关间隔。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM