如何解决SQL选择Null和Not Null值
我有一个如下表。
我想选择语言不是空的spec_id。但是当spec_id除了null之外没有其他值时,我也想选择具有null值的spec_id。 例如。 Spec_id'170470'具有语言'EN'。我只想为此spec_id选择带有Language的行不为null。并且spec_id'170464'仅具有Null值。所以我也想选择该行。
我尝试了以下查询,但它只选择语言中NOT NULL的情况。
SELECT * from temp_value w1
where w1.NAC_ID = 2453
and w1.language is not null
or (w1.language is null and not exists (select spec_id from temp_value w2
where w2.nac_id = 2453
and spec_id in (select spec_id from temp_value
where nac_id = 2453 and language is not null))
and w1.nac_id = 2453);
解决方法
我认为我们可以通过使用ROW_NUMBER
来简化此操作:
WITH cte AS (
SELECT t.*,ROW_NUMBER() OVER (PARTITION BY spec_id ORDER BY language) rn
FROM temp_value t
)
SELECT language,value,value_id,spec_id,language_id,nac_id
FROM cte
WHERE rn = 1;
这应该起作用,因为默认情况下Oracle会对NULL
进行最后排序。这意味着对于每个spec_id
记录组,非NULL
语言值(如果存在)将浮动到顶部。仅当给定的spec_id
组没有非NULL
语言记录时,才会选择NULL
记录。
编辑:
为解决可能存在两个或多个非NULL
语言记录的问题,使用先前的逻辑仅在没有非NULL
记录的情况下保留NULL
可以尝试:
WITH cte AS (
SELECT t.*,nac_id
FROM cte
WHERE language IS NOT NULL OR (rn = 1 AND language IS NULL);
,
您也可以只使用相关的子查询:在子查询中,您引用主查询的表别名。
select * from temp_value t
where language is not null
or language is null and not exists (select 'x'
from temp_value
where spec_id = t.spec_id
and nac_id = t.nac_id
and (language is not null
or value is not null
or language_id is not null));
,
您尝试过吗:
SELECT * from temp_value w1
where w1.NAC_ID = 2453
and w1.language is not null
or (w1.language is null and not exists
(select spec_id from temp_value w2
where w2.nac_id = 2453
and w2.spec_id=w1.spec_id
and language is not null
)
);
还是我错过了什么?
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。