在LOJ中返回dupes的子查询

时间:2011-10-07 12:21:10

标签: sql-server

也许是一个简单的解决方案,但由于某种原因,这让我感到沮丧。需要执行左外连接,连接条件是transaction_id和decision_id。 decision_id必须选择accept_ind ='Y'的decision_id,或者如果没有,则选择保证存在的decision_id = 1。

- 决策表 transaction_id(pk)decision)id(pk)accepted_ind
A 1 NULL
A 2
A 4 Y
B 1
B 2 Y
C 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) ) 
然而,我在子查询中返回dupes。我玩过子查询并写了一个外部查询,试图找到没有运气的问题。任何帮助都值得赞赏,因为我在多年没有触及它之后回到使用SQL。

克里斯

1 个答案:

答案 0 :(得分: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