以下是我的查询及其输出。是否可以仅使用一个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
答案 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
您可以在此处验证: