我有3张桌子。让我们说Root,Detail and Revision
我需要从Root中选择具有最高修订日期的不同代码,计算修订行可能不存在和/或在日期列中具有重复值。
Root: idRoot, Code
Detail: idDetail, price, idRoot
Revision: idRevision, date, idDetail
所以,我开始做连接查询:
select code, price, date from Root r
inner join Detail d on d.idRoot = r.idRoot
left join Revision r on d.idDetail = r.idDetail;
有这样的表格结果:
CODE|PRICE|DATE idRevision
---- ----- ----- -----------
C1 100 2/1/2016 1
C1 120 2/1/2016 3
C1 150 null 2
C1 200 1/1/2016 4
C2 300 null null
C3 400 3/1/2016 6
但我真正需要的是下一个结果:
CODE|PRICE|DATE idRevision
---- ----- ----- -----------
C1 120 2/1/2016 3
C2 300 null null
C3 400 3/1/2016 6
我已经看到了类似案例的几个答案,但从来没有使用空值和重复值:
Oracle: Taking the record with the max date
Fetch the row which has the Max value for a column
Oracle Select Max Date on Multiple records
任何形式的帮助都会非常感激
答案 0 :(得分:2)
您可以使用row_number()
:
select code, price, date
from (select code, price, date,
row_number() over (partition by code order by date desc nulls last, idRevision desc) as seqnum
from Root r inner join
Detail d
on d.idRoot = r.idRoot left join
Revision r
on d.idDetail = r.idDetail
) rdr
where seqnum = 1;