Sql 如果任何行中存在任何值,则返回该值,如果不存在,则返回空值

Sql 如果任何行中存在任何值,则返回该值,如果不存在,则返回空值,sql,Sql,我有一张桌子 Col1 Col2 300 Null 300 A 300 B 400 NULL 我需要输出,如果任何行中存在任何值,则返回它,如果不返回空值 输出: Col1 Col2 300 A 300 B 400 Null 您可以通过以下方式执行此操作: select t.* from t where t.col2 is not null union all select t.* from t where t.col2 is null and

我有一张桌子

Col1 Col2
300   Null
300   A
300   B
400   NULL
我需要输出,如果任何行中存在任何值,则返回它,如果不返回空值

输出:

Col1   Col2
300     A
300     B
400     Null
您可以通过以下方式执行此操作:

select t.*
from t
where t.col2 is not null
union all
select t.*
from t
where t.col2 is null and
      not exists (select 1 from t t2 where t2.col1 = t.col1 and t2.co2 is not null);

如果Col2具有非空值,或者如果同一Col1从未为Col2具有非空值,则返回一行

select t1.*
from tablename t1
where t1.Col2 is not null
   or not exists (select 1 from tablename t2
                  where t2.Col2 is not null
                    and t2.Col1 = t1.Col1)
CREATE TABLE #Tbl(Col1 INT, Col2 VARCHAR(100))INSERT INTO #Tbl(Col1 , Col2)
SELECT 300,Null UNION ALL SELECT 300,'A' UNION ALL SELECT 300,'B' UNION ALL
SELECT 400,NULL 
SELECT Col1 , Col2
FROM #Tbl T1
WHERE ISNULL(Col2,'') <> ''
UNION ALL
SELECT Col1 , Col2
FROM #Tbl T1
WHERE NOT EXISTS(SELECT 1 FROM #Tbl T2 WHERE T1.Col1 = T2.Col1 AND ISNULL(T2.Col2,'') <> '')