[英]How to find a column with null and not null values in same table
我有一张表,我需要在其中找到包含 null 而不是 null 值的列。 例如,该列今天有一个值,但明天变为 null。
第一个查询:
select * from test where Account Number is Not Null and LastChangedDate is Null
但是此查询带来了具有 null 值的记录,并且没有列出具有 LastChangedDate 列值的记录
以下是样本记录
AccountNumber EffectiveDate LastChangedDate
1234567 2019-05-31 2018-09-14
1234567 2019-06-30 2018-09-14
1234567 2019-07-31 NULL
第二个查询:
select * from test where Account Number is Not Null and 'LastChangedDate' is Null
但是此查询带来了具有 null 值的记录,并且没有列出具有“LastChangedDate”列值的记录
预期:能够检索具有 Null 而不是 Null 值的同一列的所有记录,并省略填充所有值的记录
使用LEAD()
:
SELECT *
FROM (
SELECT
t.*,
LEAD(LastChangedDate) OVER(PARTITION BY AccountNumber ORDER BY EffectiveDate) LastChangedDateLead
FROM test t
) x
WHERE LastChangedDate IS NULL OR LastChangedDateLead IS NULL
这将为您提供LastChangedDate
为NULL
或下一条记录(对于同一客户并由EffectiveDate
订购)的NULL
值为LastChangedDate
的记录。
注意:结果中会显示每个客户的最新记录:由于没有下一条记录,因此查询将认为其LastChangedDate
也是NULL
。
这个关于 DB fiddle 的演示与您的示例数据返回:
AccountNumber | EffectiveDate | LastChangedDate | LastChangedDateLead ------------: | :------------------ | :------------------ | :------------------ 1234567 | 30/06/2019 00:00:00 | 14/09/2018 00:00:00 | null 1234567 | 31/07/2019 00:00:00 | null | null
一起做吧:
SELECT *
FROM test
WHERE (Account Number is Not Null and 'LastChangedDate' is Null)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.