下面的查询有效,但从我读过的内容来看,这OR
并不是JOIN
获得结果的最有效方式。我认为也许我应该使用UNION
or INTERSECT
,但我不知道如何实现这一点。有人可以解释“正确的”什么来得到我的结果吗?
WITH CTE1 AS (SELECT SC, SN, COUNT(AL) AS UNEXCUSED
FROM ATT
WHERE AL = 'U'
GROUP BY SC, SN),
CTE2 AS (SELECT SC, SN, COUNT(AL) AS SUSPENDED
FROM ATT
WHERE AL = 'S'
GROUP BY SC, SN)
SELECT STU.ID, STU.SC, STU.SN,
ISNULL(CTE1.UNEXCUSED, '') AS UNX,
ISNULL(CTE2.SUSPENDED, '') AS SUS
FROM CTE2
FULL JOIN CTE1
ON CTE1.SC = CTE2.SC
AND CTE1.SN = CTE2.SN
JOIN STU
ON (CTE1.SC = STU.SC
AND CTE1.SN = STU.SN)
OR (CTE2.SC = STU.SC
AND CTE2.SN = STU.SN)
WHERE STU.SC IN (1,2,4,9,11,15)
这是输出示例:
ID SC SN UNX SUS
4291432 15 602 0 8
4296250 15 688 6 3
4216462 15 695 0 12
4916602 15 623 0 2
4295193 1 150 1 0
4215874 2 216 1 0
4005707 15 297 1 0
谢谢你。