sql-server - 如何检索具有空值和非空值的相同 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
上面的查询检索示例中所示的第二组和第三组记录,但我只想检索第一组记录
解决方案
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
推荐阅读
- python - 为什么我在类 python 中使用 super 时会出现此错误
- reactjs - 如何在反应中创建可扩展表?
- r - 用以下列中的数据填充空白值
- javascript - SAPUI5 表项重复 ID
- spring - DAO,SERVICE层是干什么用的
- typescript - “没有为突变配置架构。”
- javascript - 为什么我在解码 JSON Web 令牌时出现此错误错误:错误:0909006C:PEM 例程:get_name:没有起始行
- python - 有谁能够帮我。我被困在 Django 无法显示请求页面的这一步
- oracle-sqldeveloper - 将表数据导出到 SQL Developer 中没有的 csv 文件选项(版本 3.1.07)
- python - 如何在 python 中执行非阻塞脚本并获取其返回码?