总结mysql中的列值

时间:2012-10-22 22:24:37

标签: mysql

我有一个表“水果”,包含以下数据

id  a 
123 apple
223 orange
646 apple
757 banana
876 kiwi
989 orange

我想写一个mysql,总结列“a”的出现并将它们分成3个独立的桶:一个用于苹果,一个用于橙子,其余用于“其他”

SELECT 
     count(*) as total
     sum(if(a = 'apple',1,0)) as applecount
     , sum(if(a = 'orange',1,0)) as orangecount
     , sum(`applecount` + `orangecount` - total) as others

FROM fruits 

但是在运行查询时,会出现以下错误 字段列表中的未知列“applecount”

1 个答案:

答案 0 :(得分:3)

SELECT count(*) as total,
       sum(a = 'apple') as applecount,
       sum(a = 'orange') as orangecount,
       sum(a not in ('orange', 'apple')) as others
FROM fruits

SQLFiddle example