【问题标题】:Group data by day按天分组数据
【发布时间】:2014-10-06 13:48:40
【问题描述】:

我有一个表transaction,数据如下:

date       | status  | delivered | products
-------------------------------------------
03.10.2014 | SUCCESS |      TRUE | 4
03.10.2014 | FAILURE |      FAIL | 0
03.10.2014 | SUCCESS |      FAIL | 1
03.10.2014 | SUCCESS |      FAIL | 4
04.10.2014 | SUCCESS |      TRUE | 24
04.10.2014 | SUCCESS |      TRUE | 5
04.10.2014 | FAILURE |      FAIL | 0

现在我想按天对数据进行分组,它看起来像:

date       | success_status | failure_status | delivered | total_products
-------------------------------------------------------------------------
03.10.2014 | 3              | 1              | 1         | 9
04.10.2014 | 2              | 1              | 2         | 29

我知道如何将(products) 求和为 total_products按日期分组

但是我怎样才能在查询中获得剩余的列 success_status、failure_statusdelivered

【问题讨论】:

    标签: sql postgresql date group-by


    【解决方案1】:

    你需要做一个条件求和:

    select date, 
           sum(case when status = 'SUCCESS' and delivered then products end) as success_status,
           sum(case when status = 'FAILURE' then products end) as failure_status,
           sum(case when delivered then products end) as delivered,
           sum(products) as total_products
    from the_table
    group by date
    

    在即将到来的 9.4 版本中,您将能够更优雅地编写此代码(并且可能更清楚地了解 case 正在做什么)

    SELECT date, 
           sum(products) filter (status = 'SUCCESS' and delivered) as large_orders_amount,
           sum(products) filter (status = 'FAILURE') as failure_status,
           sum(products) filter (delivered) as delivered,
           sum(products) as total_products
    from the_table
    group by date
    

    顺便说一句:date 是一个可怕的列名称。一方面因为它也是一个保留字,但更重要的是它没有记录该列包含的内容。交货日期,接收日期,取消日期,...?

    【讨论】:

    • 非常感谢!稍微修改一下。 success_status、failure_status和delivered需要用到count(...)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-07-08
    • 1970-01-01
    • 2017-08-07
    • 2013-05-29
    • 2020-09-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多