tags:

views:

74

answers:

2

I have a table (apples) containing:

cid  date_am date_pm 
----------------------
1      1       1
2      2       1
3      1       3  
1      1       2

I asked a question earlier (badly) about how I would rank the customers in order of the number of ones(1) they had. The solution was (based on one column):

SELECT cid, sum( date_pm ) AS No_of_ones
FROM apples
WHERE date_am =1
GROUP BY cid
ORDER BY no_of_ones DESC 

This works great for one column but how would I do the same for the sum of the two columns. ie.

SELECT cid, sum( date_pm ) AS No_of_ones
FROM apples
WHERE date_am =1
add to
SELECT cid, sum( date_am ) AS No_of_ones
FROM apples
WHERE date_pm =1
GROUP by cid
ORDER by no_of_ones(added)

hope I've managed to make that clear enough for you to help -thanks

A: 
select cid, sum(case when date_pm = 1 then 1 else 0 end) + sum(case when date_am = 1 then 1 else 0 end)
from apples
group by cid
Konrad Garus
not intentionally sorry
bsandrabr
@bsandrabr: You can reverse the downvote by clicking the upvote arrow if the person has editted their answer after you cast the downvote.
OMG Ponies
A: 
select cid, sum(addone) as total from 
  (select cid, 1 as addone
   from apples
    where date_pm = 1 group by cid
    union
    select cid, 1 as addone
    from apples
    where date_am = 1 group by cid) 
group by cid order by total DESC

OR

select cid, sum(case when date_am=1 then 1 else 0 end) 
            + sum(case when date_pm=1 then 1 else 0 end) as total 
from apples 
group by CID 
order by total DESC
NickAtuShip
thanks to both the case answer you both gave worked perfectly very many thanks
bsandrabr