Question : MySQL sum() case/if

Hi All,

This is a related question.

I need to calculate the cost to get a result similar to the following;

status     chargeable    nonchargeable     cost
loan1                  100                      300     400
loan2                  500                      300     800
loan3                  100                      300     400

I've tried to use the code to calculate the cost of each but cant get the correct syntax, instead I just calculate the number of entries where the status is chargeable (that'll be the 1 else 0 bit) I have tried modifying the syntax to use a.cost but it just keeps giving an error.

Current code is below.
1:
2:
3:
4:
5:
6:
7:
8:
9:
select b.booking_type as status,
      sum(case when a.chargeable = 'Yes' then 1 else 0 end) chargeable,
      sum(case when a.chargeable = 'No' then 1 else 0 end) nonchargeable,
      sum(a.cost) as cost
from BOOKING b, ADMIN a
where b.booking_id = a.booking_id
and a.approved = "Approved"
and a.delivery_date between '2010-07-01' and '2010-07-31'
group by booking_type

Answer : MySQL sum() case/if

select b.booking_type as status,
      sum(case when a.chargeable = 'Yes' then a.cost else 0 end) chargeable,
      sum(case when a.chargeable = 'No' then a.cost else 0 end) nonchargeable,
      sum(a.cost) as cost
from BOOKING b, ADMIN a
where b.booking_id = a.booking_id
and a.approved = "Approved"
and a.delivery_date between '2010-07-01' and '2010-07-31'
group by booking_type
Random Solutions  
 
programming4us programming4us