0

次のデータを含むテーブル「果物」があります

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

列「a」の出現を合計し、それらを 3 つの個別のバケットに入れる mysql を書きたいと思います。1 つはリンゴ用、もう 1 つはオレンジ用、残りは「その他」の下にあります。

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 に答える