【问题标题】:How to count number if special type of value by day in SQL?如果在 SQL 中按天计算特殊类型的值,如何计算数字?
【发布时间】:2021-09-15 20:39:00
【问题描述】:

我的数据库中有一个如下所示的表:

time                              value_type     id
2020-05-16 10:55:33.000            upload        a11
2020-05-16 10:54:33.000            delete        a11
2020-05-15 10:52:18.000            save          b77
2020-05-15 10:51:24.000            upload        b77
2020-05-15 10:20:24.000            upload        b77

我想获取每天上传 value_types 数量的表格(我的时间列不是每天)。所以对于这个例子,它必须看起来像:

day           upload_num
2020-05-16         1
2020-05-16         2

这个 SQL 查询应该是什么样子?我不明白把时间变成天的部分。

【问题讨论】:

  • 您的样本结果在同一日期重复了两次。

标签: sql postgresql


【解决方案1】:

你似乎想要 count() 过滤:

select time::date as day, count(*) filter (where value_type = 'upload')
from t
group by day;

以上将在数据中有数据但没有上传的日子返回0。您还可以过滤 where 子句以完全删除它们:

select time::date as day, count(*)
from t
where value_type = 'upload'
group by day;

【讨论】:

    猜你喜欢
    • 2021-04-18
    • 2011-01-08
    • 1970-01-01
    • 2020-10-19
    • 1970-01-01
    • 1970-01-01
    • 2019-03-15
    • 2018-09-11
    • 1970-01-01
    相关资源
    最近更新 更多