使用不同的Where子句依靠多个列

时间:2015-11-04 21:58:54

标签: sql count insert multiple-columns

我非常感谢一些帮助创建一个查询,该查询对多个列执行计数,然后将数据插入到新表中。有一个表格,根据标记期间为每个学生存储成绩。我已经编写了一个查询来计算学生收到的Mark 1的D或F的数量。现在我想对Mark 2进行相同的计算。这是我对Mark 1代码所拥有的:

SELECT STU.ID, COUNT(GRD.M1) as DF_M1
INTO LCAPDEMO 
FROM STU JOIN
    GRD ON STU.SN = GRD.SN AND STU.SC = GRD.SC
WHERE GRD.M1 IN ('D+','D','D-','F+','F','F-')
GROUP BY STU.ID

这个过程需要每晚为Mark 1和Mark 2等级运行。

1 个答案:

答案 0 :(得分:1)

您只想要条件聚合吗?

SELECT STU.ID,
       SUM(CASE WHEN GRD.M1 IN ('D+', 'D', 'D-', 'F+', 'F', 'F-')
                THEN 1 ELSE 0 END) as DF_M1,
       SUM(CASE WHEN GRD.M2 IN ('D+', 'D', 'D-', 'F+', 'F', 'F-')
                THEN 1 ELSE 0 END) as DF_M2
INTO LCAPDEMO 
FROM STU JOIN
     GRD
     ON STU.SN = GRD.SN AND STU.SC = GRD.SC
GROUP BY STU.ID;