首页 > 解决方案 > 如何检索具有空值和非空值的相同 ID 的记录列表

问题描述

我想从 SQL 服务器中检索大于 '20150101' 的相同 AccountNumber 的记录,其中有不同的“生效日期”按升序排列,并且“LastChangedDate”字段对于最新的“生效日期”变为空,如下图第一组所示记录注意:我不希望 SQL 查询检索第 2、3、4 组记录并且只检索第 1 组记录

第一组记录

AccountNumber   EffectiveDate   LastChangedDate 
1234567         2019-07-31        2018-09-14
1234567         2019-08-18        2018-09-14
1234567         2019-09-18        NULL

第二组记录:

AccountNumber   EffectiveDate   LastChangedDate
8456566           2019-08-18     2018-09-14
8456566           2019-09-18     2018-09-14

第三组记录:

AccountNumber   EffectiveDate   LastChangedDate
8456777           2019-08-18     NULL
8456777           2019-09-18     NULL

第4组记录:

AccountNumber   EffectiveDate   LastChangedDate
8456777           2019-08-18     NULL
8456777           2019-09-18     NULL
8456777           2019-08-18     2018-09-14

以下是仅检索第二组和第三组记录但不检索第一组记录的当前查询

select count(AccountNumber) 
from table where EffectiveDate > '20150101' and LastChangedDate is NULL or LastChangedDate is NOT NULL
group by AccountNumber
having AccountNumber > 1

select count(AccountNumber) 
from table where EffectiveDate > '20150101' and LastChangedDate is NULL or LastChangedDate is NOT NULL
group by AccountNumber
having AccountNumber > 1

上面的查询检索示例中所示的第二组和第三组记录,但我只想检索第一组记录

标签: sql-server

解决方案


Just add parenthesis:

select count(AccountNumber) 
from table where (EffectiveDate > '20150101' and LastChangedDate is NULL) or LastChangedDate is NOT NULL
group by AccountNumber
having AccountNumber > 1

推荐阅读