连续查找重复项

时间:2016-06-01 10:17:01

标签: sql

我有一个名为TEST的表。某些字段具有NULL值

Country City   Street   House
US      NULL   Avenue   14
UK      London NULL     15
NULL    NULL   NULL     NULL
NULL    NULL   Central  16

我需要显示只有一个NULL的项目。

所以输出应该是:

Country City   Street House
US      NULL   Avenue 14
UK      London NULL   15

我有愚蠢的解决方案,只需比较所有可能的列对并检查NULL。

就像这样:

 SELECT * FROM TEST
 WHERE NOT (
 (country='NULL' AND city='NULL')
 OR (country='NULL' AND street='NULL')
 OR (coutry='NULL' AND house='NULL')
 OR (city='NULL' AND street='NULL')
 OR (city='NULL' AND house='NULL')
 OR (street='NULL' AND house='NULL')
 )

它有效,但要明白这是非常低效的。

您能推荐更优雅的解决方案吗?

2 个答案:

答案 0 :(得分:4)

select * from TEST
WHERE  
  CASE WHEN country = 'NULL' THEN 1 ELSE 0 END
+ CASE WHEN city= 'NULL' THEN 1 ELSE 0 END
+ CASE WHEN Street = 'NULL' THEN 1 ELSE 0 END
+ CASE WHEN House = 'NULL' THEN 1 ELSE 0 END = 1

答案 1 :(得分:0)

select *
from test1 
where
length(nvl(country,'@')||nvl(City,'@')||nvl(street,'@')||nvl(house,'@'))-
length(replace(nvl(country,'@')||nvl(City,'@')||nvl(street,'@')||nvl(house,'@'),'@',null))=1