如何使用多个条件计算跨列的总计?

时间:2014-11-13 16:56:53

标签: sql-server tsql

我正在尝试为每个程序代码添加每个年级的总计。共有超过26个程序代码,它们分散在6列中。我需要按照学校,等级来计算程序代码,就像输出节目一样。

对不起,我没有代码,但我甚至不知道从哪里开始。

数据集:

enter image description here

所需的输出:

enter image description here

输出的总数按学校按年级分组。

SQL可以这样做,如果是这样,请问怎么样?

谢谢!

1 个答案:

答案 0 :(得分:1)

这应该让你开始

select 
school_code
,grade_level 
,sum(case when [program code 1] = 'A' 
            or [program code 2] = 'A' 
            or [program code 3] = 'A' 
            or [program code 4] = 'A' 
            or [program code 5] = 'A' 
            or [program code 6] = 'A' 
            then 1  else 0 end )as A
,sum(case when [program code 1] = 'B' 
            or [program code 2] = 'B' 
            or [program code 3] = 'B' 
            or [program code 4] = 'B' 
            or [program code 5] = 'B' 
            or [program code 6] = 'B' 
            then 1  else 0 end )as B
,sum(case when [program code 1] = 'C' 
            or [program code 2] = 'C' 
            or [program code 3] = 'C' 
            or [program code 4] = 'C' 
            or [program code 5] = 'C' 
            or [program code 6] = 'C' 
            then 1  else 0 end )as C

--... Repeat the above or however many program codes you have

from
    --Whatever table you need to use 


group by 
School_Code
,Grade_level