是否可以只使用一个select语句构建我的查询?

时间:2012-08-05 04:39:42

标签: sql tsql

以下是我的查询及其输出。是否可以仅使用一个select语句构建我的查询(我的查询中有两个)?这是出于性能目的。

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

enter image description here

1 个答案:

答案 0 :(得分:3)

您可以在CASE函数中执行通过/失败的SUM语句...然后您不需要CTE:

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

您可以在此处验证:

http://sqlfiddle.com/#!3/99cd4/7