如果我有一张如下表格
Person | Category | Fav Colors
----- | ----------- | ------
one | Native | RED
one | Native | GREEN
two | Non-Native | RED
two | Non-Native | BLUE
three | Native | RED
three | Native | GREEN
如何根据每种颜色的每个类别的人数来获取数据?
即。
Fav Color | Native | Non-Native
--------- | --------| --------
RED | 2 | 1
GREEN | 2 | 0
BLUE | 0 | 1
答案 0 :(得分:2)
你可以这样做:
select `Fav Colors` as `Fav Color`,
count(case category when 'Native' then 1 end) Native,
count(case category when 'Non-Native' then 1 end) `Non-Native`
from tbl
group by `Fav Colors`
注意:您没有提及排序顺序的任何要求。如果您需要一个,您只需列出order by
子句中的列号:
order by 2 desc
答案 1 :(得分:0)
我是在Oracle中完成的,所以不得不稍微重命名列,但这里有一个想法:
select FAV_COLORS,SUM(CASE CATEGORY WHEN 'NATIVE' THEN 1 ELSE 0 END) AS NATIVE,SUM(CASE CATEGORY WHEN 'NON-NATIVE' THEN 1 ELSE 0 END) AS NON_NATIVE
from TEMP
GROUP BY FAV_COLORS