2011-10-07 61 views
0

也許是一個簡單的解決方案,但由於某種原因,這使我絆倒了。需要執行左外連接,並且連接條件是transaction_id和decision_id。 decision_id必須選擇accept_ind ='Y'的decision_id,或者如果沒有,那麼選擇decision_id = 1,這將保證存在。LOJ中的子查詢返回模糊

--Decision表 的transaction_id(PK)決定)ID(PK)accepted_ind
A 1 NULL
A 2
甲4 Y
乙1
乙2 Y
Ç1 Y
D 1 N
D 2 O
D 3 Y

DECLARE decision TABLE (
    transaction_id NCHAR(1),  
    decision_id INT,  
    accepted_ind NCHAR(1) NULL 
) 

    INSERT decision VALUES  
    ('A' , 1 , NULL),  
    ('A' , 2 , ''),  
    ('A' , 4 , 'Y'),  
    ('B' , 1 , ''),  
    ('B' , 2 , 'N'), 
    ('C' , 1 , 'Y'),  
    ('D' , 1 , 'N'),  
    ('D' , 2 , 'O'),  
    ('D' , 3 , 'Y') 


    DECLARE load TABLE (
    transaction_id NCHAR(1),  
    consignee CHAR(240), 
    miles INT 
) 

    INSERT load VALUES  
    ('A' , 'COSTCO' , 32),  
    ('B' , 'SAMS CLUB' , 43),  
    ('C' , 'WG&R' , 62),  
    ('D' , 'SAMS CLUB' , 15) 

LOJ正在加載一個加載表並加入decsion表以僅返回一行。我想我需要第二套眼睛。這是我目前試圖去上班很簡單:

LEFT OUTER JOIN L_DECISION with (nolock)  
    on L_LOAN.transaction_id = L_DECISION.transaction_id and 
    L_DECISION.decision_id = (select decision_id 
      from L_DECISION d2 with (nolock) 
      where cust_accept_ind = 'Y' OR 
     (NOT EXISTS (select 1 FROM l_decision d3 with (nolock) 
     where cust_accept_ind = 'Y' and 
     d3.transaction_id = d2.transaction_id) and 
     decision_id = 1)) 

然而,我是在子查詢返回dupe。我玩過子查詢並編寫了一個外部查詢來試圖找到問題,但沒有運氣。任何幫助都會受到讚賞,因爲在經過多年未觸及它之後,我重返與SQL一起工作。

克里斯

+0

[SELECT DISTINCT](http://www.w3schools.com/sql/sql_distinct。 ASP)...? – ewall

回答

1

我覺得子查詢的條件是不正確的,請嘗試更改LOJ這樣:

LEFT OUTER JOIN L_DECISION with (nolock) 
    on L_LOAN.transaction_id = L_DECISION.transaction_id and 
L_DECISION.decision_id = case when 
         (select count(*) 
          from L_DECISION d2 (nolock) 
          where cust_accept_ind = 'Y' 
          and d2.transaction_id = L_DECISION.transaction_id) = 0 
      then 1 else (select top 1 d3.decision_id 
          from L_DECISION d3 (nolock) 
          where cust_accept_ind = 'Y' 
          and d3.transaction_id = L_DECISION.transaction_id) end 
+0

完美!謝謝你的幫助,這正是我所需要的,我也從中學到了一種新技術! –