Oracle-Join多次使用同一表,但条件不同

时间:2018-11-01 06:31:16

标签: sql oracle11g

这是我的情况,

enter image description here

SELECT 
A.TAB1_COL1,B.TAB2_COL4,C.TAB2_COL4 
FROM TABLE1 A, 
LEFT OUTER JOIN 
    (SELECT * FROM 
        (SELECT TAB2_COL1, TAB2_COL2, TAB2_COL4, ROW_NUMBER() OVER (PARTITION BY TAB2_COL1,TAB2_COL2 ORDER BY TAB2_COL3 DESC ) AS ROW_NUM 
            FROM TABLE2 
            WHERE TAB2_COL2=2
        ) WHERE ROW_NUM=1
    ) B ON A.TAB1_COL1=B.TAB2_COL1 
LEFT OUTER JOIN 
    (SELECT * FROM 
        (SELECT TAB2_COL1, TAB2_COL2, TAB2_COL4, ROW_NUMBER() OVER (PARTITION BY TAB2_COL1,TAB2_COL2 ORDER BY TAB2_COL3 DESC ) AS ROW_NUM 
            FROM TABLE2 WHERE TAB2_COL2=5
        ) WHERE ROW_NUM=1
    ) C ON A.TAB1_COL1=C.TAB2_COL1 AND A.TAB1_COL2=C.TAB2.COL5 
LEFT OUTER JOIN 
    (SELECT * FROM 
        (SELECT TAB2_COL1, TAB2_COL2, TAB2_COL4, ROW_NUMBER() OVER (PARTITION BY TAB2_COL1,TAB2_COL2 ORDER BY TAB2_COL3 DESC ) AS ROW_NUM 
            FROM TABLE2 WHERE TAB2_COL2=8
        ) WHERE ROW_NUM=1
    ) D ON A.TAB1_COL1=D.TAB2_COL1

此代码将起作用。但是,我多次与同一张表联接。就我而言,大约是25倍。参考表有大约2亿条记录。分区来删除公仔要花很多时间。

任何其他有效的书写方式可以使其处理更快。请帮助。

谢谢

1 个答案:

答案 0 :(得分:1)

如果我理解正确,则可以使用条件聚合:

select t1.tab1_col1,
       max(case when tab2_col2 = 2 then tab2_col4 end),
       max(case when tab2_col2 = 5 then tab2_col4 end),
       max(case when tab2_col2 = 8 then tab2_col4 end)
from table1 t1 left join
     (select t2.*,
             row_number() over (partition by tab2_col1, tab2_col2 order by tab2_col3 desc) as seqnum
      from table2 t2
     ) t2
     on t1.tab1_col1 = t2.tab2_col1
group by t1.tab1_col1;