我有变量ID和代码的数据。示例数据如下所示:
ID Code
abc 00
def 00
ghi 00
def 23
jkl 00
mno 20
pqr 24
ID可以具有多个不同代码的值。我正在尝试计算每个ID的所有可能的代码组合(共有15种)
我的代码:
select id, code from data.test
where id in (select id from data.test where code = 00 )
and id in ('abc','def','ghi','jkl','mno','pqr')
正常工作(返回4行),但是此代码:
select id, code from data.test
where id not in (select id from data.test where code = 23)
and id in ('abc','def','ghi','jkl','mno','pqr')
返回0行?它应该返回3行。
我正在使用Teradata SQL Assistant版本15.00.0.02。
任何帮助,将不胜感激。
原因之一,not in
与子查询失败,是因为价值观的一个(id
你的情况)是NULL
。在这种情况下,NOT IN
表达式永远不会返回true。解决此问题的一种方法:
select id, code
from data.test
where id not in (select id from data.test where code = 23 and id is not null) and
id in ('abc', 'def', 'ghi', 'jkl', 'mno', 'pqr')
另一种方法是使用NOT EXISTS
:
select t.id, t.code
from data.test t
where not exists (select 1 from data.test t2 where t.code = 23 and t2.id = t.id) and
t.id in ('abc', 'def', 'ghi', 'jkl', 'mno', 'pqr')
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句