加入具有非空值的多个列并提取具有最高优先级的记录

时间:2016-12-10 18:08:58

标签: sql oracle

我有一组聚合记录,我需要将其与另一个包含&列的表联系起来没有空值并且在存在多个匹配时拉出具有最高优先级的记录。表2列可以具有空值。

表1

col1 col2 col3 col4 

表2

col1 col2 col3 col4 col5 col6 col7 priority

1 个答案:

答案 0 :(得分:1)

使用row_number()

select t1.*, t2.*
from t1 join
     (select t2.*,
             row_number() over (partition by ?? order by priority desc) as seqnum
      from t2
     ) t2
     on t1.?? = t2.??
where seqnum = 1;

??表示用于将两个表连接在一起的列。例如,如果您希望col1上的匹配具有最高优先级:

select t1.*, t2.*
from t1 join
     (select t2.*,
             row_number() over (partition by col1 order by priority desc) as seqnum
      from t2
     ) t2
     on t1.col1 = t2.col1
where seqnum = 1;