簡體   English   中英

如果在 SQL 中滿足第一個條件,則停止檢查其他條件

[英]Stop checking other conditions if first condition is met in SQL

我在一個表格中有數據,如下所示:

ID  ContactId  EffectiveToDate  EffectiveFromDate  Maximum_EffectiveToDate ID_count
1    68        Null             10-2-2005           11-3-2006                2
2    68        11-3-2006        13-1-2006           11-3-2006                2
3    78        Null             01-01-2000          Null                     1
4    80        10-10-2004       19-09-2003          10-10-2004               1
5    82        15-08-2002       19-06-2001          15-08-2002               3
6    82        10-06-2001       01-01-2000          15-08-2002               3
7    82        Null             20-10-2004          15-08-2002               3
8    85        10-06-2005       10-05-2004          10-06-2005               2
9    85        11-07-2004       10-04-2003          10-06-2005               2

ID-count 是ContactId列的計數。 我想 select 以ContactId出現一次(不重復)的方式排列行,條件是:

  1. 選擇出現一次的 ContactId 的數據(即 ID_count =1)
  2. 如果 ContactId 出現多次(即 ID_count >1),則只選擇 EffectiveToDate 為 Null 的行
  3. 如果 ContactId 出現多次(即 ID_count > 1)並且 EffectiveToDate 不是 null 則選擇EffectiveToDate值等於 Maximum_EffectiveToDate 的行

為了滿足上述條件,我編寫了以下 SQL 代碼:

Select * from table
where (ID_count = 1 or (ID_count > 1 AND EffectiveToDate is Null) or
       (ID_count > 1 AND EffectiveToDate is not Null AND EffectiveToDate = Maximum_EffectiveToDate))

上面代碼的問題是它兩次返回 ContactId 82 和 68 的行。 EffectiveToDate一行,Null 一行, EffectiveToDate等於Maximum_EffectiveToDate一行。 SQL 中有什么方法可以停止其余條件以檢查第一個條件是否為真?

您可以使用row_number為每一行分配一個排名並返回第一個符合條件的行:

select ID, ContactId, EffectiveToDate, EffectiveFromDate, Maximum_EffectiveToDate, ID_count
from (
  select *, 
    Row_Number() over(
      partition by ContactId
      order by ID_count, EffectiveToDate, Iif(EffectiveToDate = Maximum_EffectiveToDate, 0, 1)
    ) rn
  from t
)t
where rn = 1;

您可以嘗試使用UNION來達到預期的效果。

select * from table where ContactId in (
    select ContactId from table group by ContactId having count(1) = 1)
union
select * from table where ContactId in (
    select ContactId from table group by ContactId having count(1) > 1)
and isnull(EffectiveToDate, '') = ''
union
select * from (
    select row_number() over (partition by ContactId order by EffectiveToDate desc) rn,
        * from table where isnull(EffectiveToDate, '') != '')
where rn = 1 and ContactId not in (select ContactId from table group by ContactId having count(1) = 1)

修改第三個條件以檢查 null 記錄是否存在

select *
from t
where id_count = 1 or
      (id_count > 1 and effectivetodate is null) or
      (not exists(select 1 from t t1 where t1.contactid = t.contactid and t1.effectivetodate is null) and effectiveToDate = Maximum_EffectiveToDate)
;    

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM