SQL查询获取字段值分布

时间:2010-06-16 21:00:09

标签: sql pivot

我有一张超过100万张测试成绩记录的表格,基本上有一个独特的score_ID,一个subject_ID和一个人给出的分数。大多数受试者的得分范围是0-3,但有些得分范围为0-4。大约有25个可能的科目。

我需要制作一个分数分布报告,如下所示:

subject_ID     0    1    2    3    4
----------    ---  ---  ---  ---  ---
1             967  576  856  234  
2             576  947  847  987  324
.
.

因此,它按subject_ID对数据进行分组,然后显示在该主题中给出特定分数值的次数。

非常感谢任何生成此指针的SQL指针。

1 个答案:

答案 0 :(得分:6)

Select subject_id
    , Sum( Case When Score = 0 Then 1 Else 0 End ) As [0]
    , Sum( Case When Score = 1 Then 1 Else 0 End ) As [1]
    , Sum( Case When Score = 2 Then 1 Else 0 End ) As [2]
    , Sum( Case When Score = 3 Then 1 Else 0 End ) As [3]
    , Sum( Case When Score = 4 Then 1 Else 0 End ) As [4]
From Table
Group By subject_id