如何使用表中的多个计数

时间:2019-01-28 06:48:40

标签: sql select count

我有问题 我的桌子:

ID State   Club
--------------
1  Alabama Red
2  Alabama Green
3  Florida Red
4  Alaska  Red

我需要这个结果

示例:

Alabama,count(red),Count(Green),Count(blue),Count(Yellow)
Alaska,count(red),Count(Green),Count(blue),Count(Yellow)
Florida,count(red),Count(Green),Count(blue),Count(Yellow)

如何选择查询???

2 个答案:

答案 0 :(得分:1)

使用条件聚合

select state, 
       count(case when club = 'Red' then 1 end) Red,
       count(case when club = 'Green' then 1 end) Green,
       count(case when club = 'Blue' then 1 end) Blue,
       count(case when club = 'Yellow' then 1 end) Yellow
from table
group by state

答案 1 :(得分:1)

另一个使用PIVOT的答案。

SELECT * FROM
(
SELECT ID,State,Club FROM myTable 
) s
PIVOT
(
COUNT(ID) FOR Club IN ([Red],[Green],[Yellow])
) pvt