如何在sql中汇总数据?

时间:2015-07-07 17:36:24

标签: sql

我有一个数据表,需要在excel上的报告表中提取值的计数, 但我需要在报告中显示任何行和列。

我的表格如下:

ID  Val  Sets
1   aa   25
2   aa   26
3   bb   25
4   cc   27
5   aa   27
6   aa   25

我的报告采用以下格式:

    25  26  27
aa  2   1   1
bb  1   0   0
cc  0   0   1

1 个答案:

答案 0 :(得分:2)

使用条件聚合:

select val,
       sum(case when sets = 25 then 1 else 0 end) as [25],
       sum(case when sets = 26 then 1 else 0 end) as [26],
       sum(case when sets = 27 then 1 else 0 end) as [27]
from tablename
group by val

使用透视:

select val,
       [25],
       [26],
       [27]
from tablename
pivot(count(id) for sets in([25],[26],[27]))p