gpt4 book ai didi

带有 SUM CASE 语句的 SQL GROUP BY

转载 作者:行者123 更新时间:2023-12-05 01:31:13 24 4
gpt4 key购买 nike

我知道有很多这样的问题:

SQL GROUP BY CASE statement with aggregate function

但我试过这样做:

with T as (select col1 , SUM(CASE WHEN col2 = 1 THEN col3 ELSE 0 END) AS Totale
from tabella
group by col1, col2)
select col1, Totale
from T
group by col1, Totale

但我得到
col1  |  Totale
---------------
1 0
1 70
2 0
2 90

代替:
 col1  |  Totale
---------------
1 70
2 90

那有什么问题?

更新:

我的不好,我尽量保持简单,但我做得太过分了..我要做的是:
with T as (select col1 , SUM(CASE WHEN col2 = 1 THEN col3 ELSE 0 END) AS TotaleA,
SUM(CASE WHEN col2 = 2 THEN col3 ELSE 0 END) AS TotaleB,
(...)
from tabella
group by col1, col2)
select col1, TotaleA, TotaleB
from T
group by col1, TotaleA, TotaleB

解决方案是在分组中没有 col2 ......我害怕“在选择列表中无效,因为它不包含在聚合函数或 GROUP BY 子句中”,但它不是......我可以标记一个评论为正确答案?

最佳答案

您还可以使用子查询来解决此问题:

SELECT 
col1,
SUM(A) TotalA,
SUM(B) TotalB
FROM
(
select col1,
CASE WHEN col2 = 1 THEN col3 ELSE 0 END A,
CASE WHEN col2 = 2 THEN col3 ELSE 0 END B
from tabella
) t
GROUP BY Col1

关于带有 SUM CASE 语句的 SQL GROUP BY,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25288847/

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