按天分组数据

时间:2014-10-06 13:48:40

标签: sql postgresql date group-by

我的表交易,数据如下:

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

我知道如何总和(产品)为total_products 按日期分组

但是如何在查询中获得剩余的列 success_status,failure_status 已发送

1 个答案:

答案 0 :(得分:3)

你需要做一个条件总和:

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是一个可怕的名字。因为它也是一个保留字,但更重要的是它没有记录列包含的内容。交货日期,收货日期,取消日期,......?