SQL选择跨多个表,每个连接表中包含最大日期

时间:2013-03-11 17:25:16

标签: sql oracle join max

我有一个Oracle 11 SQL查询,我从4个表中提取数据,所有表都是通过ID加入的。连接到第一个表的3个表都有一个ACTIVE_IND值,需要为“Y”和生效日期(EFF_DATE),我需要每个记录的最大生效日期。

我有一个可以在这里工作的查询,但是想知道是否有更优化/有效/有效的编写方式,因为它看起来有点慢。我目前使用的是这样的:

SELECT DISTINCT A.TABLE1_ID,
                A.TABLE1_COL1,
                B.TABLE2_COL2,
                C.TABLE3_COL3,
                D.TABLE4_COL4
FROM TABLE1 A,
     TABLE2 B,
     TABLE3 C,
     TABLE4 D
WHERE B.TABLE2_ID = A.TABLE1_ID
  AND B.TABLE2_ACTIVE_IND = 'Y'
  AND B.TABLE2_EFF_DATE =
    (SELECT MAX (B2.TABLE2_EFF_DATE)
     FROM TABLE2 B2
     WHERE B2.TABLE2_ID = B.TABLE2_ID
       AND B2.TABLE2_ACTIVE_IND = 'Y')
  AND C.TABLE3_ID = A.TABLE1_ID
  AND C.TABLE3_ACTIVE_IND = 'Y'
  AND C.TABLE3_EFF_DATE =
    (SELECT MAX (C2.TABLE3_EFF_DATE)
     FROM TABLE3 C2
     WHERE C2.TABLE3_ID = C.TABLE3_ID
       AND C2.TABLE3_ACTIVE_IND = 'Y')
  AND D.TABLE4_ID = A.TABLE1_ID
  AND D.TABLE4_ACTIVE_IND = 'Y'
  AND D.TABLE4_EFF_DATE =
    (SELECT MAX (D2.TABLE4_EFF_DATE)
     FROM TABLE4 D2
     WHERE D2.TABLE4_ID = D.TABLE4_ID
       AND D2.TABLE4_ACTIVE_IND = 'Y')
ORDER BY A.TABLE1_ID;

1 个答案:

答案 0 :(得分:2)

尝试:

SELECT DISTINCT A.TABLE1_ID,
                A.TABLE1_COL1,
                B.TABLE2_COL2,
                C.TABLE3_COL3,
                D.TABLE4_COL4
FROM TABLE1 A
JOIN (SELECT T2.*, 
             RANK() OVER (PARTITION BY TABLE2_ID ORDER BY TABLE2_EFF_DATE DESC) RN
      FROM TABLE2 T2
      WHERE TABLE2_ACTIVE_IND = 'Y') B ON B.TABLE2_ID = A.TABLE1_ID AND B.RN=1
JOIN (SELECT T3.*, 
             RANK() OVER (PARTITION BY TABLE3_ID ORDER BY TABLE3_EFF_DATE DESC) RN
      FROM TABLE3 T3
      WHERE TABLE3_ACTIVE_IND = 'Y') C ON C.TABLE3_ID = A.TABLE1_ID AND C.RN=1
JOIN (SELECT T4.*, 
             RANK() OVER (PARTITION BY TABLE4_ID ORDER BY TABLE4_EFF_DATE DESC) RN
      FROM TABLE4 T4
      WHERE TABLE4_ACTIVE_IND = 'Y') D ON D.TABLE4_ID = A.TABLE1_ID AND D.RN=1
ORDER BY A.TABLE1_ID;