将相关子查询限制为仅一个记录

时间:2013-06-25 15:07:39

标签: correlated-subquery

我正在尝试使用相关子查询,但我试图将其限制为“最佳”记录。当我使用SQL非常类似于后面的内容时,每个BigTable.identifier得到两行,我希望只有一行。在“联盟”声明中,下半场比上半场更令人满意。但是,有时需要上半年。有任何想法吗?这是代码:

select 
  BigTable.identifier,
  Correlated.ID,
  Correlated.Effective_Date,
  Correlated.Period_Number

from
  BigTable

inner join

( 
select
  TOP 2147483647
  Table3.identifier,
  Table4.Effective_Date,
  Table4.Period_Number

from
  Table3
inner join Table4 on Table3.matching_key = Table4.matching_key
where
  Table4.Period_Number = 0
order by Table4.Effective_Date desc

UNION

 select 
  TOP 2147483647
  Table3.Identifer,
  Table4.Effective_Date,
  Table4.Period_Number
 from
   Table3
 inner join Table5 on Table3.matching-key = Table5.matching-key
 inner join Table4 on Table5.key1 = Table4.key1 and
    Table5.key2 = Table4.key2
where
   Table4.period_number = 1 
order by Table4.Effective_Date desc
) as Correlated 

on BigTable.identifier = Correlated.identifier

1 个答案:

答案 0 :(得分:0)

如果该UNION中的每个子查询都有一些条件,如果它不是首选,则排除该行,您将永远不会在UNION中看到不太优选的行。 所以,如果每个都有一个NOT EXISTS(......在union的另一侧有一个更好的行......),你可以在根处消除不太喜欢的行。

我不清楚你想如何使用生效日期。假设你的意思是你更喜欢Period = 1,但如果生效日期更少,你更喜欢Period = 0,那么这样的东西可能会起作用。

select 
  BigTable.identifier,
  Correlated.ID,
  Correlated.Effective_Date,
  Correlated.Period_Number

from
  BigTable

inner join

( 
select
  TOP 2147483647
  Table3.identifier,
  Table4.Effective_Date,
  Table4.Period_Number

from
  Table3
inner join Table4 on Table3.matching_key = Table4.matching_key
where
  Table4.Period_Number = 0
 AND NOT EXISTS 
   (select 1 
    from Table5 T5 inner join Table4 T4
    on T5.key1 = T4.key1 and T5.key2 = T4.key2 
    where Table3.matching-key = T5.matching-key
      and (T4.Effective_Date >= Table4.Effective_Date  and T4.Period_Number = 1)
   )
order by Table4.Effective_Date desc

UNION

 select 
  TOP 2147483647
  Table3.Identifer,
  Table4.Effective_Date,
  Table4.Period_Number
 from
   Table3
 inner join Table5 on Table3.matching-key = Table5.matching-key
 inner join Table4 on Table5.key1 = Table4.key1 and
    Table5.key2 = Table4.key2
where
   Table4.period_number = 1 
 AND NOT EXISTS 
   (select 1 
    from Table4 T4
    where Table3.matching-key = T4.matching-key
      and (T4.Period_Number > 0)
      and (T4.Effective_Date > Table4.Effective_Date  and T4.Period_Number = 0)
   )
order by Table4.Effective_Date desc
) as Correlated 

on BigTable.identifier = Correlated.identifier