如何在逐个分组

时间:2015-08-10 13:32:39

标签: postgresql group-by aggregate-functions psql case-when

INPUT:

我有一张表格如下:

    date   | is_shipped | is_realised | mrp  
----------+------------+-------------+------
 12022015 |          1 |           1 | 1000
 12022015 |          0 |           1 | 2000
 12022015 |          1 |           0 | 3000
 13022015 |          1 |           1 | 1500
 13022015 |          0 |           1 | 2500
 13022015 |          1 |           0 | 3500

问题陈述:

我想按日期对行进行分组以获得总mrp以及与is_shipped = 1is_realised = 1对应的mrp。例如,12022015上的总mrp为1000 + 2000 + 3000 = 6000. is_shipped = 1上与12022015对应的总mrp为1000 + 3000 = 4000.对应于{{1}的总mrp } is_realised = 1上的内容是1000 + 2000 = 3000。

预期输出

所以,我的结果应该类似于:

12022015

擅自解决方案:

我尝试了以下查询,但不起作用:

    date   | shipped_mrp | realised_mrp | mrp  
----------+-------------+--------------+------
 12022015 |        4000 |         3000 | 6000
 13022015 |        5000 |         4000 | 7500

错误:

我收到以下错误:

  

列“rev.is_realised”必须出现在GROUP BY子句中或使用   在集合函数LINE 2中:CASE WHEN is_realised = 1

2 个答案:

答案 0 :(得分:4)

将case语句移到sum函数中:

select 
  date, 
  sum(CASE WHEN is_shipped = 1 THEN mrp ELSE 0 END) AS shipped_mrp,
  sum(CASE WHEN is_realised = 1 THEN mrp ELSE 0 END) AS realised_mrp,
  sum(mrp) AS mrp
from rev
group by date;

Sample SQL Fiddle

答案 1 :(得分:1)

如果使用 PG9.4 + ,请使用效率更高的FILTER子句:

SELECT "date",
       sum(mrp) FILTER (WHERE is_shipped = 1) AS shipped_mrp,
       sum(mrp) FILTER (WHERE is_realised = 1) AS realised_mrp,
       sum(mrp) AS mrp
FROM rev
GrOUP BY 1;