這裏有一些方法
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)
方法1:
SELECT * FROM @t WHERE Id NOT IN (SELECT Id FROM @t WHERE IsnotValid=1)
方法2:
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
運行此針對上述樣本數據返回2個記錄其中id = 1是0。我只想ID = 2,其中所有IsNotValid is 0 – soulia
@soulia這個查詢*完全*與接受的答案的方法1相同,就是你說的爲你工作的答案。你輸入的內容是否正確? – gcochard
嗨格雷格 - 是的,你是對的。我一定錯了什麼。感謝您將此引起我的注意。 – soulia