有关分组的SQL查询

时间:2012-08-04 18:50:29

标签: tsql

第一张图片是我的查询输出。现在我想对主题进行分组,使其变得像第二个图像。可能吗?谢谢你的帮助。

select Subject, Grade, case when Grade >= 50 Then '1' else '0' end as Pass, case when Grade < 50 Then '1' else '0' end as Fail from Grade_report

输出:

enter image description here

我想要的是:

enter image description here

1 个答案:

答案 0 :(得分:0)

您的规格不是很准确;您在合并记录的等级中期望的是什么数字?它应该只写1或0还是汇总通过和失败列的总和?

以下内容将生成您的输出,成绩为MAX,通过/失败信息为SUM

WITH GradePassFail AS (
    SELECT 
        Subject, 
        Grade, 
        CASE WHEN Grade >= 50 THEN 1 ELSE 0 END AS Pass, 
        CASE WHEN Grade < 50 THEN 1 ELSE 0 END AS Fail 
    FROM Grade_report
)
SELECT Subject, MAX(Grade) AS Grade, SUM(Pass) AS Pass, SUM(Fail) AS Fail
FROM GradePassFail
GROUP BY Subject