我有一张桌子
Col1 Col2
300 Null
300 A
300 B
400 NULL
如果任何行中存在任何值,则需要输出,如果不是返回,则返回null值
输出:
Col1 Col2
300 A
300 B
400 Null
答案 0 :(得分:1)
您可以这样做:
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);
答案 1 :(得分:1)
如果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)
答案 2 :(得分:-1)
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,'') <> '')