![](/img/trans.png)
[英]If first condition is true then stop fetching from the other conditions in where clause of a SQL query
[英]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
出現一次(不重復)的方式排列行,條件是:
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.