使用GroupBy进行SQL计数查询

时间:2014-07-19 22:34:31

标签: sql-server select pivot

我的表格中的数据格式如下

ID CSLang VBLang Level Occurrence
1  FALSE  TRUE   1 - 4  1
2  FALSE  TRUE   5 - 9  1
3  FALSE  TRUE   0 - 0  1
4  TRUE   FALSE  1 - 4  1
5  TRUE   FALSE  5 - 9  1
6  TRUE   FALSE  10 - 15 1
7  TRUE   TRUE   0 - 0  1
8  FALSE  FALSE  0 - 0  1


我想得到如下数据(我想要CSharp和VB的数量是真实的按级别分组)

Level CountCS CountVB       
0 - 0   1       2       
1 - 4   1       1       
5 - 9   1       1       
10 - 15 1       0

1 个答案:

答案 0 :(得分:2)

您可以尝试如下(假设您使用的是MySQL)。查看演示小提琴http://sqlfiddle.com/#!2/08b00f/4

select level,
sum(CSharpLang = 'true') as CountCSharp,
sum(VBLang = 'true') as CountVBLang     
from table1
group by level
order by level

每次更新,如果您使用的是SQL Server,那么您可以执行以下操作。演示小提琴http://sqlfiddle.com/#!3/7fa05/3

select level,
sum(case when CSLang = 'true' then 1 else 0 end) as CountCSharp,
sum(case when VBLang = 'true' then 1 else 0 end) as CountVBLang     
from table1
group by level
order by level