我在SQL Server中有这个查询:
SELECT DISTINCT
D214.DESTIMATED,
D214.LINSEQNO,
H214.SHPID
FROM IN_214_HDR H214
JOIN IN_214_DTL D214 ON H214.TRANNO = D214.TRANNO
WHERE H214.SHPID = 'NGB8264646'
它将返回此结果集
DESTIMATED LINSEQNO SHPID
2014-08-24 00:00:00.000 1 NGB8264646
2014-09-09 00:00:00.000 2 NGB8264646
2014-09-09 00:00:00.000 3 NGB8264646
2014-09-23 00:00:00.000 4 NGB8264646
使用不同的H214.SHPID我会得到不同数量的行返回,它们都会有一个LINSEQNO = 1
DESTIMATED LINSEQNO SHPID
2014-08-24 00:00:00.000 1 NGB8262321
2014-09-12 00:00:00.000 2 NGB8262321
2014-09-18 00:00:00.000 3 NGB8262321
2014-10-23 00:00:00.000 4 NGB8262321
2014-10-29 00:00:00.000 5 NGB8262321
2014-11-09 00:00:00.000 6 NGB8262321
我需要的是一个返回相同列的查询,但我只需要LINSEQ最大的行。所以每个人都需要这样的结果集......
DESTIMATED LINSEQNO SHPID
2014-09-23 00:00:00.000 4 NGB8264646
和
DESTIMATED LINSEQNO SHPID
2014-11-09 00:00:00.000 6 NGB8264646
LINSEQNO的最小值将为1,但最大值可以是任何> 1。
答案 0 :(得分:2)
SELECT TOP 1 D214.DESTIMATED,
D214.LINSEQNO,
H214.SHPID
FROM IN_214_HDR H214
JOIN IN_214_DTL D214 ON H214.TRANNO = D214.TRANNO
WHERE H214.SHPID = 'NGB8264646'
ORDER BY LINSEQNO DESC
答案 1 :(得分:0)
使用窗口功能:
select DESTIMATED, LINSEQNO, SHPID
from (select D214.DESTIMATED, D214.LINSEQNO, H214.SHPID,
row_number() over (partition by H214.SHPID order by D214.LINSEQNO desc) as seqnum
from IN_214_HDR H214 joi
IN_214_DTL D214
on H214.TRANNO = D214.TRANNO
) t
where seqnum = 1;