2013-03-11 74 views
2

我有一個Oracle 11 SQL查詢,我從4個表中抽取所有由ID連接的數據。加入第一個表的每個表都有一個ACTIVE_IND值,該值必須是'Y'和生效日期(EFF_DATE),並且我需要每個記錄的生效日期最長。SQL在多個表中選擇,每個連接表中的最大日期爲

我有一個查詢,在這裏工作,但想知道是否有一個更優化/有效/有效的方式寫它,因爲它似乎有點慢。我目前使用這樣看起來是什麼:

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; 

回答

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; 
+0

感謝馬克。一旦我將3個RN標籤調整爲唯一的,似乎可以工作。我最初得到了'ORA-00918:列明確定義'的錯誤。 – Brandon 2013-03-11 18:37:53

+0

哎呀,我似乎錯過了預選賽,例如「B.RN = 1」。 – Brandon 2013-03-11 18:44:23

+0

@Brandon:最初,我忘了讓RN標籤獨一無二 - 大約半小時後,我注意到我的疏忽並修復了它。 – 2013-03-12 10:26:49

相關問題