0

以下是我的查询及其输出。是否可以仅使用一个 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

在此处输入图像描述

4

1 回答 1

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

于 2012-08-05T05:08:03.410 回答