SQL计数聚合查询

时间:2012-07-24 14:27:31

标签: sql aggregate counting

我有以下查询:

select prop_id
    , sum(amount)bnp_spent
    , (select count(*) from cost where cost_type = 'Direct Cost')direct
    , (select count(*) from cost where cost_type = 'Burden Cost')burden
from cost                                     
group by prop_id

子查询不是我想要的。通过从成本表中选择,我得到所有道具的直接或负担的总成本

我想要的是每个prop_id的直接和负担成本计算

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:2)

试试这个:

select prop_id, sum(amount) as bnp_spent,
       sum(case when cost_type = 'Direct Cost' then 1 else 0 end) as direct,
       sum(case when cost_type = 'Burden Cost' then 1 else 0 end) as burden
from cost
group by prop_id