34,587
社区成员
发帖
与我相关
我的任务
分享
--创建测试数据:
go
if OBJECT_ID('tbl')is not null
drop table tbl
go
create table tbl(
col1 varchar(5),
col2 varchar(5),
col3 varchar(5),
col4 varchar(5),
col5 varchar(5),
col6 varchar(5),
col7 varchar(5),
col8 varchar(5)
)
insert tbl
select '1',5,'2',5,'3','4','5','6' union all
select '1','2','3',null,null,null,null,'4' union all
select '2','2',null,'3','4','5','6','7' union all
select '3',2,3,'2','3',3,'4',2
--静态实现方法
--"+"想加统计各个“case when else”的结果来达到目的:
select *,
case when col1 is not null then 1 else 0 end+
case when col2 is not null then 1 else 0 end+
case when col3 is not null then 1 else 0 end+
case when col4 is not null then 1 else 0 end+
case when col5 is not null then 1 else 0 end+
case when col6 is not null then 1 else 0 end+
case when col7 is not null then 1 else 0 end+
case when col8 is null then 1 else 0 end as notnull
from tbl
--动态实现方法
declare @str varchar(8000)
set @str=''
select @str= @str+'+ case when ' + name +' is null then 1 else 0 end'+char(13)+char(10)
--char(13)+char(10)实现换行
from syscolumns where id = OBJECT_ID('tbl')
--print @str
set @str='select col1,col2,col3,col4,col5,col6,col7,col8 from(select *,'+@str+' as notnull from tbl)a where notnull=0'
--print @str
exec(@str)
/*
1 5 2 5 3 4 5 6
3 2 3 2 3 3 4 2
*/
--> 测试数据:#tt
if object_id('tempdb.dbo.#tt') is not null drop table #tt
go
create table #tt([A] int,[B] int,[C] numeric(2,1),[D] numeric(2,1))
insert #tt
select 42000001,1000,1,null union all
select 42000001,2001,1.5,null union all
select 42000001,3001,1.7,3.1 union all
select 42000002,1000,1,3 union all
select 42000002,2001,2,6 union all
select 42000002,2003,3,3 union all
select 42000002,2005,7,0
--------------开始查询--------------------------
select * from #tt a where not exists(select 1 from #tt b where a.[A]=b.[A] and (b.[C] is null or b.[D] is null))
----------------结果----------------------------
/*
A B C D
----------- ----------- --------------------------------------- ---------------------------------------
42000002 1000 1.0 3.0
42000002 2001 2.0 6.0
42000002 2003 3.0 3.0
42000002 2005 7.0 0.0
(4 行受影响)
*/
select diatinct a
from tab a
where not exists (
select 1 from tab
where a = a.a
and (c is null or d is null)
)
select distinct A.A
from TB A
where not exists(select 1 from TB where A.A = A and (c is null or d is null))
select * from tab where A not in
(
select distinct A from tab where c is null or d is null
)
select distinct A from TB where c is not null and D is not null