1

我正在尝试使用相关子查询,但我试图将其限制为“最佳”记录。当我使用与以下内容非常相似的 SQL 时,每个 BigTable.identifier 有两行,我希望只有一个。在“UNION”语句中,后半部分比前半部分更可取。但是,有时需要前半部分。有任何想法吗?这是代码:

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
4

1 回答 1

0

如果该 UNION 中的每个子查询都有一些条件,如果该行不太受欢迎,则将其排除在外,那么您将永远不会在 UNION 中看到不太受欢迎的行。因此,如果每个人都有一个 NOT EXISTS(.... 在联合的另一侧有一个更好的行 ....),您将在根处消除不太喜欢的行。

我不清楚你想如何使用生效日期。假设您的意思是您更喜欢 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
于 2013-06-25T17:35:02.010 回答