2016-11-22 69 views

回答

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) 
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
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,'') <> '') 
相关问题