gpt4 book ai didi

postgresql - 如何在 group by 子句后应用 case when 语句

转载 作者:行者123 更新时间:2023-11-29 14:06:52 26 4
gpt4 key购买 nike

输入:

我有一张看起来像这样的表:

    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。 12022015 上对应于 is_shipped = 1 的总 mrp 为 1000 + 3000 = 4000。在 12022015 上对应于 is_realised = 1 的总 mrp 为 1000 + 2000 = 3000。

预期输出

所以,我的结果应该是这样的:

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

尝试的解决方案:

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

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

错误:

我收到以下错误:

column "rev.is_realised" must appear in the GROUP BY clause or be used in an aggregate function LINE 2: CASE WHEN is_realised = 1

最佳答案

将 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

关于postgresql - 如何在 group by 子句后应用 case when 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31920953/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com