我有一个查询返回,例如,此结果
ID Name Year Age
0 NULL 2013 23
1 Luis NULL 24
2 Jose 2010 NULL
3 Fernando 2003 43
我想获取所有行,如果对于某些列(在本例中为Name,Year,Age),至少一行具有空值,否则为0行。例如,在公开示例中,我得到4行,因为每列至少有一个空值。
另一方面:
ID Name Year Age
0 NULL 2013 23
1 Luis NULL 24
2 Jose 2010 34
3 Fernando 2003 43
年龄没有空值,所以我得到0行。
提前致谢!
答案 0 :(得分:4)
使用此:
with cte as (
select case when count(*)=count(year) or count(*) = count(name) or count(*)=count(age) then 0 else 1 end as val from data
)
select data.* from data,cte where 1 = cte.val
答案 1 :(得分:1)
@mrida的版本是完美的,但我使用CTE只计算计数以便更容易支持。
/* test tables:
create table t1 (ID int,Name varchar(100),[Year] int, Age int)
insert t1
select 0,NULL,2013,23 union all
select 1,'Luis',NULL,24 union all
select 2,'Jose',2010,NULL union all
select 3,'Fernando',2003,43
create table t2 (ID int,Name varchar(100),[Year] int, Age int)
insert t2
select 0,NULL,2013,23 union all
select 1,'Luis',NULL,24 union all
select 2,'Jose',2010,34 union all
select 3,'Fernando',2003,43
*/
--for Jose with undefined age
with cte as (select count(*) as AllCount,count(year) as YearsCount,count(name) as NamesCount,count(age) as AgesCount from t1)
select t1.* from t1,cte
where not (cte.AllCount=cte.YearsCount or cte.AllCount=cte.NamesCount or cte.AllCount=cte.AgesCount)
--for 34-aged Jose :)
with cte as (select count(*) as AllCount,count(year) as YearsCount,count(name) as NamesCount,count(age) as AgesCount from t2)
select t2.* from t2,cte
where not (cte.AllCount=cte.YearsCount or cte.AllCount=cte.NamesCount or cte.AllCount=cte.AgesCount)