sql - 按星期几分组

标签 sql postgresql

我有一个表 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 nullnull 所以只有 true 会被计算在内。

在较新的版本中有一个聚合过滤器:

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

关于sql - 按星期几分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39000498/

相关文章:

sql - 如何在 SQL 中计算点积

asp.net - 从 aspnet 应用程序在 ubuntu 终端中执行命令

sql - 总计运行...有一个转折

c# - Nhibernate 一对一映射代码

Mysql:获取按字段分组的具有最大值的行

php - 使用 javascript 登录 (php)

sql - 函数 oracle 到 postgresql

Mysql 单元包含需要格式化才能用于 IN 语句的包含列表?

java - ORA-00904 错误

ruby-on-rails - Rails - PG::数据类型不匹配:错误