我只想为每个STO_PART只显示一行,即具有MAX(TRL_DATE)的那一行
我发现ROW_NUMBER()...可能有用,但是我无法通过带有联接的查询正确地完成操作。
SELECT STO_PART, STO_PART_ORG, STO_STORE, BIS_BIN, TRL_ORDER, TRL_DATE
FROM R5STOCK inner join R5PARTS on PAR_CODE = STO_PART and STO_PART_ORG = PAR_ORG
inner join R5BINSTOCK on (BIS_STORE = STO_STORE and BIS_PART = STO_PART and BIS_PART_ORG = STO_PART_ORG)
left join R5TRANSLINES on (TRL_PART = PAR_CODE and PAR_ORG = TRL_PART_ORG and TRL_TYPE = 'RECV')
WHERE PAR_NOTUSED != '+' and BIS_QTY > 0 and STO_STORE in ('116-01', '138-05', '156-01', '216-01', '228-01', '282-01')
and TRL_STORE = STO_STORE and TRL_ORDER is not null
GROUP BY STO_PART, STO_PART_ORG, STO_STORE, BIS_BIN, TRL_ORDER, TRL_DATE
实际结果和预期结果。现在应该显示带有红线的结果,因为还有另一个STO_PART的TRL_DATE较高
ROW_NUMBER个查询
SELECT STO_PART, STO_PART_ORG, STO_STORE, BIS_BIN, TRL_ORDER, TRL_DATE
FROM (SELECT STO_PART, STO_PART_ORG, STO_STORE, BIS_BIN, TRL_ORDER, TRL_DATE, ROW_NUMBER() over (partition by STO_PART ORDER BY TRL_DATE DESC) as MAX_DATE
FROM R5STOCK inner join R5PARTS on PAR_CODE = STO_PART and STO_PART_ORG = PAR_ORG
inner join R5BINSTOCK on (BIS_STORE = STO_STORE and BIS_PART = STO_PART and BIS_PART_ORG = STO_PART_ORG)
left join R5TRANSLINES on (TRL_PART = PAR_CODE and PAR_ORG = TRL_PART_ORG and TRL_TYPE = 'RECV')
WHERE PAR_NOTUSED != '+' and BIS_QTY > 0 and STO_STORE in ('116-01', '138-05', '156-01', '216-01', '228-01', '282-01')
and TRL_STORE = STO_STORE and TRL_ORDER is not null) X
WHERE MAX_DATE = 1
答案 0 :(得分:0)
在这种情况下,通常可以在每个分区中为所需的订单创建虚拟字段。
SELECT
*
FROM
(
SELECT STO_PART, STO_PART_ORG, STO_STORE, BIS_BIN, TRL_ORDER, TRL_DATE,
InvertedOrder = ROW_NUMBER() OVER PARTITION BY (STO_PART ORDER BY TRL_ORDER DESC)
FROM R5STOCK
inner join R5PARTS on PAR_CODE = STO_PART and STO_PART_ORG = PAR_ORG
inner join R5BINSTOCK on (BIS_STORE = STO_STORE and BIS_PART = STO_PART and BIS_PART_ORG = STO_PART_ORG)
left join R5TRANSLINES on (TRL_PART = PAR_CODE and PAR_ORG = TRL_PART_ORG and TRL_TYPE = 'RECV')
WHERE PAR_NOTUSED != '+' and BIS_QTY > 0 and STO_STORE in ('116-01', '138-05', '156-01', '216-01', '228-01', '282-01')
and TRL_STORE = STO_STORE and TRL_ORDER is not null
GROUP BY STO_PART, STO_PART_ORG, STO_STORE, BIS_BIN, TRL_ORDER, TRL_DATE
)
WHERE
InvertedOrder=1