我有这样的桌子:
id | Name | Buy
---+-------+-----
1 | Alice | Apple
2 | Alice | Banana
3 | Alice | Apple
4 | Bob | Apple
如何编写显示如下所示结果的一行SQL命令?
Name | Apple | Banana
------+-------+-------
Alice | 2 | 1
Bob | 1 | 0
答案 0 :(得分:1)
使用case when
select Name,sum(case when Buy='Apple' then 1 else0 end) as Apple,
sum(case when Buy='Banana' then 1 else 0 end) as Banana
from yourtable
group by Name
http://sqlfiddle.com/#!9/5ab22a/2
Name Apple Banana
Alice 2 1
Bob 1 0