我有一个包含以下数据的表“fruits”
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”
最佳答案
SELECT count(*) as total,
sum(a = 'apple') as applecount,
sum(a = 'orange') as orangecount,
sum(a not in ('orange', 'apple')) as others
FROM fruits
关于mysql - 汇总mysql中的列值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13020822/