带有SUM CASE语句的SQL GROUP BY

时间:2014-08-13 14:27:56

标签: sql sql-server

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

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子句中#34;但是它不是..我可以将评论标记为正确答案吗?

2 个答案:

答案 0 :(得分:2)

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

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

答案 1 :(得分:1)

这是一个想法。不知道为什么你把它包裹在一个cte但为什么不让它更简单?

select col1 
    , SUM(col3) AS Totale
from tabella
where col2 = 1
group by col1