对sql select语句中的不同列使用sum()和count()

时间:2014-08-25 17:56:18

标签: sql count group-by subquery

我还在学习写一些复杂的查询,所以如果这听起来很简单,请原谅我:

我有一张包含以下数据的表格:

    Id        Service   Type      SubType    Status    Charge
------------------------------------------------------------------
    A         S1        Pr         100        Active     20
    A         S1        Pr         50         Active     10
    A         S2        Sec        20         Inactive   30
    A         S2        Sec        100        Inactive   50
    A         S2        Sec        50         Inactive   15 
    B         S3        Pr         100        Active     90
    B         S3        Pr         100        Active     40

结果:

Id   Active_Service  Inactive_Service  Total_Charge
----------------------------------------------------------
A         1               1                 20
B         1               0                 130

其中 当Total_Charge的{​​{1}}为Service:“Pr”和Id时,会计算Type:100

我已经通过一种方式(使用SubType函数)将查询写入显示(Cust_id,Total_Charge)。但是,显示列:(Active_Service,Inactive_Service)要求我们在同一个sql中以另一种方式(sum())使用分组。我们如何编写一个查询来实现所需的结果?

2 个答案:

答案 0 :(得分:0)

你想要的是条件聚合:

select id,
       sum(case when status = 'Active' then 1 else 0 end) as Active,
       sum(case when status = 'Inactive' then 1 else 0 end) as Inactive,
       sum(case when type = 'PR' and Subtype = 100 then charge end) as TotalCharge
from data d
group by id;

答案 1 :(得分:0)

您可以使用max查找id是否有任何有效服务,sum将值添加到一起:

select  Id
,       max(case when status = 'Active' then 1 else 0 end) as Active_Service
,       max(case when status = 'Inactive' then 1 else 0 end) as Inactive_Service
,       sum(case when type = 'PR' and SubType = 100 then charge end) as Total_Charge
from    YourTable
group by 
        Id