这里有一些方法
Declare @t table (Id Int, IsnotValid Bit)
Insert Into @t Values(1,0),(1,0),(1,1),(2,0),(2,0),(3,1),(3,1)
方法一:
SELECT * FROM @t WHERE Id NOT IN (SELECT Id FROM @t WHERE IsnotValid=1)
方法二:
SELECT *
FROM @t T1
WHERE IsnotValid = 0
AND NOT EXISTS (
SELECT *
FROM @t T2
WHERE T1.Id = T2.Id
AND T2.IsnotValid <> 0)
方法3:
SELECT *
FROM @t T1
WHERE IsnotValid = 0
AND Id NOT IN (
SELECT Id
FROM @t T2
WHERE T2.IsnotValid <> 0)
方法4:
SELECT T1.*
FROM @t T1
LEFT OUTER JOIN @t T2 ON T1.Id = T2.Id AND T2.IsnotValid <> 0
WHERE T1.IsnotValid = 0
AND T2.Id IS NULL
方法5:
select Id,IsnotValid
from (select t.*, SUM(CAST(IsnotValid AS INT)) over (partition by Id) as sumflag
from @t t
) t
where sumflag = 0
方法6:
;with cte as(
Select
Id = Case when x.Id is null then y.Id else x.Id end
,x.CountFor0
,y.CountFor1
From
(Select Id,CountFor0 = count(*)
from @t
where IsnotValid = 0
group by Id )x
Full Join
(Select Id,CountFor1 =count(*)
from @t
where IsnotValid = 1
group by Id )y
On x.Id = y.Id)
Select Id
From cte
where CountFor1 is null
结果
Id IsnotValid
2 0
2 0