CodeKingPlusPlus
CodeKingPlusPlus

Reputation: 16081

SQL counting aggregate query

I have the following query:

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

The subqueries are NOT WHAT I WANT. By selecting from the cost table I get the total number of costs that are Direct or Burden for all props

What I want is the count of direct and burden costs for each prop_id

Any help is greatly appreciated.

Upvotes: 0

Views: 65

Answers (1)

Gordon Linoff
Gordon Linoff

Reputation: 1269753

Try this:

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

Upvotes: 2

Related Questions