我有两个疑问。此查询给出正确的结果:
SELECT SFRSTCR_PIDM
FROM SATURN.SFRSTCR
INNER JOIN SATURN.SSBSECT
ON SFRSTCR_TERM_CODE = SSBSECT_TERM_CODE
AND SFRSTCR_CRN = SSBSECT_CRN
AND (SFRSTCR_RSTS_CODE LIKE 'R%'
OR SFRSTCR_RSTS_CODE LIKE 'W%')
AND SFRSTCR_CREDIT_HR >= 1
AND SSBSECT_SUBJ_CODE IN ('ASTR', 'BIOL', 'CHEM', 'ENVS', 'GEOL', 'PHYS')
AND SSBSECT_CRSE_NUMB NOT LIKE '%L'
AND SFRSTCR_TERM_CODE BETWEEN '&BeginAY' AND '&EndAY'
INNER JOIN SATURN.SHRDGMR
ON SFRSTCR_PIDM = SHRDGMR_PIDM
AND SHRDGMR_GRST_CODE = 'AW'
AND SHRDGMR_TERM_CODE_GRAD BETWEEN '&BeginAY' AND '&EndAY'
AND SHRDGMR_MAJR_CODE_1 = '&MajorCode'
GROUP BY SFRSTCR_PIDM
HAVING COUNT(SFRSTCR_CRN) = 2
ORDER BY SFRSTCR_PIDM
它返回 8 条符合条件的记录。
此查询给出不正确的结果:
SELECT SFRSTCR_PIDM,
SSBSECT_SUBJ_CODE,
SSBSECT_CRSE_NUMB
FROM SATURN.SFRSTCR
INNER JOIN SATURN.SSBSECT
ON SFRSTCR_TERM_CODE = SSBSECT_TERM_CODE
AND SFRSTCR_CRN = SSBSECT_CRN
AND (SFRSTCR_RSTS_CODE LIKE 'R%'
OR SFRSTCR_RSTS_CODE LIKE 'W%')
AND SFRSTCR_CREDIT_HR >= 1
AND SSBSECT_SUBJ_CODE IN ('ASTR', 'BIOL', 'CHEM', 'ENVS', 'GEOL', 'PHYS')
AND SSBSECT_CRSE_NUMB NOT LIKE '%L'
AND SFRSTCR_TERM_CODE BETWEEN '&BeginAY' AND '&EndAY'
INNER JOIN SATURN.SHRDGMR
ON SFRSTCR_PIDM = SHRDGMR_PIDM
AND SHRDGMR_GRST_CODE = 'AW'
AND SHRDGMR_TERM_CODE_GRAD BETWEEN '&BeginAY' AND '&EndAY'
AND SHRDGMR_MAJR_CODE_1 = '&MajorCode'
GROUP BY SFRSTCR_PIDM,
SSBSECT_SUBJ_CODE,
SSBSECT_CRSE_NUMB
HAVING COUNT(SFRSTCR_CRN) = 2
ORDER BY SFRSTCR_PIDM
我想要它做的是返回 16 条记录:第一个查询中的 8 个 SFRSTCR_PIDM 应该每个重复两次,并且每条记录应该有一个 SSBSECT_SUBJ_CODE 和一个 SSBSECT_CRSE_NUMB。它实际上做的是给我 8 条完全不同的 SFRSTCR_PIDM 记录。
我不太确定问题出在哪里,但我认为有某种方法可以操纵 GROUP BY 子句以使其正常工作。我会很感激一些帮助。
编辑:这可行,但必须有一个更简单的解决方案:
SELECT iv1.SFRSTCR_PIDM,
sect2.SSBSECT_SUBJ_CODE,
sect2.SSBSECT_CRSE_NUMB
FROM SATURN.SFRSTCR stcr2
INNER JOIN SATURN.SSBSECT sect2
ON stcr2.SFRSTCR_TERM_CODE = sect2.SSBSECT_TERM_CODE
AND stcr2.SFRSTCR_CRN = sect2.SSBSECT_CRN
AND sect2.SSBSECT_SUBJ_CODE IN ('ASTR', 'BIOL', 'CHEM', 'ENVS', 'GEOL', 'PHYS')
AND sect2.SSBSECT_CRSE_NUMB NOT LIKE '%L'
AND stcr2.SFRSTCR_TERM_CODE BETWEEN '&BeginAY' AND '&EndAY'
INNER JOIN (SELECT stcr1.SFRSTCR_PIDM
FROM SATURN.SFRSTCR stcr1
INNER JOIN SATURN.SSBSECT sect1
ON stcr1.SFRSTCR_TERM_CODE = sect1.SSBSECT_TERM_CODE
AND stcr1.SFRSTCR_CRN = sect1.SSBSECT_CRN
AND (stcr1.SFRSTCR_RSTS_CODE LIKE 'R%'
OR stcr1.SFRSTCR_RSTS_CODE LIKE 'W%')
AND stcr1.SFRSTCR_CREDIT_HR >= 1
AND sect1.SSBSECT_SUBJ_CODE IN ('ASTR', 'BIOL', 'CHEM', 'ENVS', 'GEOL', 'PHYS')
AND sect1.SSBSECT_CRSE_NUMB NOT LIKE '%L'
AND stcr1.SFRSTCR_TERM_CODE BETWEEN '&BeginAY' AND '&EndAY'
INNER JOIN SATURN.SHRDGMR dgmr1
ON stcr1.SFRSTCR_PIDM = dgmr1.SHRDGMR_PIDM
AND dgmr1.SHRDGMR_GRST_CODE = 'AW'
AND dgmr1.SHRDGMR_TERM_CODE_GRAD BETWEEN '&BeginAY' AND '&EndAY'
AND dgmr1.SHRDGMR_MAJR_CODE_1 = '&MajorCode'
GROUP BY stcr1.SFRSTCR_PIDM
HAVING COUNT(stcr1.SFRSTCR_CRN) = 2) iv1
ON stcr2.SFRSTCR_PIDM = iv1.SFRSTCR_PIDM
ORDER BY iv1.SFRSTCR_PIDM,
sect2.SSBSECT_SUBJ_CODE,
sect2.SSBSECT_CRSE_NUMB