0

我有一张包含以下数据的“水果”表

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”

4

1 回答 1

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 示例

于 2012-10-22T22:27:12.183 回答