【问题标题】:How to get count of a column between a certain date range without changing the Where clause in SQL如何在不更改 SQL 中的 Where 子句的情况下获取某个日期范围内的列数
【发布时间】:2020-07-29 02:07:29
【问题描述】:

我有一个包含帐号、组类别和日期的表格。

我有一个这样的查询

Select count(AccNum)
FROM Table
Where date BETWEEN '2020-02-01' AND '2020-03-31'
AND
group IN ('groupA','groupB')

现在有什么办法可以让它像这样工作

Select count(AccNum) Where date between 2020-02-01 AND '2020-02-31' AS CountFebuary, count(AccNum) Where date between 2020-03-01 AND '2020-02-31' AS CountMarch,
FROM Table
Where date BETWEEN '2020-02-01' AND '2020-03-31'
AND
group IN ('groupA','groupB')

我希望能够获得每个月的帐户总数,而无需为其编写单独的查询。这可能吗?

【问题讨论】:

    标签: sql date group-by count pivot


    【解决方案1】:

    你可以做条件聚合:

    select 
        sum(case when date >= '2020-02-01' and date < '2020-03-01' then 1 else 0 end) cnt_february,
        sum(case when date >= '2020-03-01' and date < '2020-04-01' then 1 else 0 end) cnt_march
    from mytable
    where 
        date >= '2020-02-01' and date < '2020-04-01'
        and group IN ('groupA','groupB')
    

    既然你只想要两个月的数据,那我们可以稍微缩短一下条件表达式:

    select 
        sum(case when date <  '2020-03-01' then 1 else 0 end) cnt_february,
        sum(case when date >= '2020-03-01' then 1 else 0 end) cnt_march
    from mytable
    where 
        date >= '2020-02-01' and date < '2020-04-01'
        and group IN ('groupA','groupB')
    

    如果您正在运行 MySQL,我们可以缩短一些:

    select 
        sum(date <  '2020-03-01') cnt_february,
        sum(date >= '2020-03-01') cnt_march
    from mytable
    where 
        date >= '2020-02-01' and date < '2020-04-01'
        and group IN ('groupA','groupB')
    

    附注:group 在大多数数据库中是一个保留字,因此不适合作为列名。

    【讨论】:

      猜你喜欢
      • 2019-07-15
      • 1970-01-01
      • 2019-04-12
      • 2022-01-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多