条件聚合与SUM和COUNT组合(不同列)

时间:2015-03-26 12:45:15

标签: sql count pivot sql-optimization

我有一张桌子:

State      City     Class   Population      
 S1         SC1       A         10
 S1         SC2       B         5
 S1         SC3       A         7
 S2         S2C1      B         6
 S2         S2C2      A         13
 S2         S2C3      A         10

查询所需的结果集:

States     Count_of_Class_A_Cities     Total Population of State
  S1                 2                           22
  S2                 2                           29

这可以使用条件求和和计数聚合吗?或枢轴?而不是在select语句中使用内部计数或内部求和语句。

感谢。

2 个答案:

答案 0 :(得分:1)

    SELECT
        State AS States ,
        COUNT(CASE WHEN Class = 'A' THEN 1 END) AS Count_of_Class_A_Cities ,
        SUM(Population) AS Total_Population_of_State
FROM TABLE

    GROUP BY
        State 

答案 1 :(得分:1)

仅计算城市时的用例:

   select state,
          sum(case when class = 'A' then 1 else 0 end) as Count_of_Class_A_Cities,
          sum(Population) as Total_Population_of_State
   from tablename
   group by state