将两列组合在一起

时间:2010-03-12 21:29:31

标签: sql sum

我有一张表(苹果),其中包含:

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

我之前(严重地)问了一个问题,即如何根据客户的数量(1)对客户进行排名。解决方案是(基于一栏):

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

这适用于一列,但我如何对两列的总和做同样的事情。 即。

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)

希望我已经设法清楚地表达了你的帮助-thanks

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

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