2017-02-15 41 views
3

我試圖將這兩個表連接在一起,以顯示記錄在基地和空歷史中。我遇到的問題是左外連接。當BO.val2 = 0時:我想讓連接只使用BO.VAL5 = TR.VAL5,但是當BO.val2 = TR.val2時,我希望它用於連接。下面的代碼是一個正確的想法。如果您有任何關於如何做到這一點的建議,那將非常棒!SQL:左外部連接,可以切換哪些列加入,具體取決於列內的數據

SELECT DISTINCT  
    BO.RUN_DATE, 
    BO.val2, 
    BO.val3, 
    BO.val4, 
    BO.VAL5 
    TR.DTDATE, 
    TR.val2, 
    TR.val3, 
    TR.val4, 
    TR.val5 
FROM BASE BO      
LEFT OUTER JOIN HISTORY AS TR ON CASE 
    WHEN BO.val2 = 0 and BO.VAL5 = TR.VAL5 THEN ???? 
    WHEN BO.val2 = TR.val2 and BO.VAL5 = TR.VAL5 then ??? 
    ELSE ?? 
    END 
WHERE TRUNC(BO.POST_DATE)= TRUNC(SYSDATE) 
ORDER BY BO.VAL4 ; 

回答

0

你需要做的是加入歷史兩次,使用您的不同條件。然後您可以使用COALESCE()返回數據

SELECT DISTINCT 
     BO.RUN_DATE, 
     BO.val2, 
     BO.val3, 
     BO.val4, 
     BO.VAL5 
     COALESCE(TR.DTDATE, TR2.DTDATE) AS DTDATE, 
     COALESCE(TR.val2, TR2.val2) AS val2, 
     COALESCE(TR.val3, TR2.val3) AS val3, 
     COALESCE(TR.val4, TR2.val4) AS val4, 
     COALESCE(TR.val5, TR2.val5) AS val5 
    FROM BASE BO      
    LEFT OUTER JOIN History AS TR ON TR.VAL5 = BO.VAL5 
    LEFT OUTER JOIN History AS TR2 ON TR2.VAL2 = BO.VAL2 
    WHERE TRUNC(BO.POST_DATE)= TRUNC(SYSDATE) 
    ORDER BY BO.VAL4 ; 
1

您的兩個變體都有BO.VAL5 = TR.VAL5的共同點。

邏輯的第二部分是BO.val2 = TR.val2BO.val2 = 0

所以,最終的情況應該是:

SELECT DISTINCT 
    BO.RUN_DATE, 
    BO.val2, 
    BO.val3, 
    BO.val4, 
    BO.VAL5, 
    TR.DTDATE, 
    TR.val2, 
    TR.val3, 
    TR.val4, 
    TR.val5 
FROM 
    BASE AS BO 
    LEFT JOIN HISTORY AS TR 
     ON BO.VAL5 = TR.VAL5 AND (BO.val2 = 0 OR BO.val2 = TR.val2) 
WHERE 
    TRUNC(BO.POST_DATE) = TRUNC(SYSDATE) 
ORDER BY BO.VAL4; 
+0

謝謝弗拉基米爾! –

+0

@BeauJenkins,歡迎來到Stack Overflow。 請注意,在這裏說'謝謝'的首選方式是通過 提高投票的好問題和有用的答案(一旦你有足夠的聲譽這樣做),並接受任何 問題最有用的答案,你問(這也給你一個小小的提升,以你的聲望 )。 請參閱[關於]頁面以及[如何在此提問 ?](http://stackoverflow.com/help/how-to-ask) –