在下面的查询中,我试图写一个条件来获得最小的term_cd,但这并没有给出确切的结果。任何人都可以帮助我。
要求:
TNT.STU_ID
和TNT.MINOR_CD
的每个唯一组合,请显示TNT.TERM_CD
至少TNT.TERM_SEQ_NUM
代码:
SELECT
pt.[TERM_CD]
FROM
[SR0TNT] pt
WHERE
TERM_SEQ_NUM = (SELECT MIN(TERM_SEQ_NUM)
FROM [SR0TNT] AS t2
WHERE pt.STU_ID = t2.STU_ID
--and pt.TERM_CD = t2.TERM_CD
AND pt.STU_ID = '003899725 '
答案 0 :(得分:1)
很少有办法真正做到这一点..这是最简单的方法之一。
SELECT
STU_ID,
MINOR_CD,
[TERM_CD],
TERM_SEQ_NUM
FROM
(SELECT
STU_ID,
MINOR_CD,
[TERM_CD],
TERM_SEQ_NUM,
ROW_NUMBER() OVER (PARTITION BY STU_ID,MINOR_CD ORDER BY TERM_SEQ_NUM) Rn
FROM
[SR0TNT]
WHERE
STU_ID = '003899725 '
) pt
WHERE
Rn = 1
如果要使用你的方法,它会是这样的。
SELECT
pt.[TERM_CD]
FROM
[SR0TNT] pt
WHERE
pt.STU_ID = '003899725 '
AND pt.TERM_SEQ_NUM = (
SELECT MIN(TERM_SEQ_NUM)
FROM [SR0TNT] AS t2
WHERE pt.STU_ID = t2.STU_ID AND pt.MINOR_CD = t2.MINOR_CD
)
你也可以自己加入..
SELECT
pt.[TERM_CD]
FROM
[SR0TNT] pt
JOIN (SELECT
STU_ID,
MINOR_CD,
MIN(TERM_SEQ_NUM) AS TERM_SEQ_NUM
FROM
[SR0TNT]
GROUP BY
STU_ID, MINOR_CD) t2 ON t2.STU_ID = pt.STU_ID
AND t2.MINOR_CD = pt.MINOR_CD
AND t2.TERM_SEQ_NUM = pt.TERM_SEQ_NUM
WHERE
pt.STU_ID = '003899725 '
答案 1 :(得分:0)
select pt.[TERM_CD] --You don't need MINOR_CD as a SELECT field?
FROM [SR0TNT] pt
INNER JOIN ( --This inner join will act like a filter to exclude rows that do not have the minimum TERM_SEQ_NUM
select TNT.TERM_CD,TNT.STU_ID,TNT.MINOR_CD, MIN(TNT.TERM_SEQ_NUM) as minm
FROM [SR0TNT] TNT
GROUP BY TNT.TERM_CD,TNT.STU_ID,TNT.MINOR_CD
) SUB
ON pt.TERM_CD = SUB.TERM_CD
AND pt.MINOR_CD = SUB.MINOR_CD
AND pt.STU_ID = SUB.STU_ID
AND pt.TERM_SEQ_NUM = SUB.minm
WHERE pt.STU_ID = '003899725 '