2013-03-28 46 views
3

假設我有以下表格 Person tablepersonStatus table如何選擇他們的狀態只在一個集合中的記錄?

declare @Persons table 
(PersonId int) 

insert into @Persons select 10 
insert into @Persons select 11  
insert into @Persons select 12 
insert into @Persons select 13 
insert into @Persons select 14  

declare @PersonStatus table 
(id int,statuss int) 
insert into @PersonStatus (id,statuss) values(14,4) 
insert into @PersonStatus (id,statuss) values(10,0) 
insert into @PersonStatus (id,statuss) values(10,0) 
insert into @PersonStatus (id,statuss) values(11,1) 
insert into @PersonStatus (id,statuss) values(10,1) 
insert into @PersonStatus (id,statuss) values(11,2) 
insert into @PersonStatus (id,statuss) values(12,0) 
insert into @PersonStatus (id,statuss) values(12,1) 
insert into @PersonStatus (id,statuss) values(12,2) 
insert into @PersonStatus (id,statuss) values(13,1) 
insert into @PersonStatus (id,statuss) values(13,3) 

現在我想找到的人ID的他們的狀態都只是在這個集合{0,1,2} 結果是---「10,11,12

怎麼做?

+0

如果你計劃你的 「限制」 的標準是動態的(或參數),檢查出我問一會兒回來的問題:http://stackoverflow.com/questions/7492699/how-can-i-structure-a-query-to-give-me-only-the-rows-that-match-all-values-in-a。除了我的輸入是限制集的CSV字符串外,它和您的一樣。 – Gibron 2013-03-28 07:28:05

回答

3
SELECT ID 
FROM PersonStatus 
GROUP BY ID 
HAVING SUM(CASE WHEN statuss IN (0, 1, 2) THEN 1 ELSE 0 END) >= 1 AND 
     SUM(CASE WHEN statuss NOT IN (0, 1, 2) THEN 1 ELSE 0 END) = 0 
+0

+1使用'HAVING' :) – Gibron 2013-03-28 07:31:59

2

試試這個

SELECT DISTINCT ID 
FROM @PersonStatus PT 
WHERE NOT EXISTS (SELECT * FROM @PersonStatus WHERE statuss not in (0,1,2) AND id=PT.id) 
+0

如果結果集爲'{0,1,4}',那麼結果如何?使用您的查詢,結果將包括'status = 2'和'status = 3'的'id' – praveen 2013-03-28 07:19:38

+1

@praveen然後替換'statuss> 2'與'statuss in(0,1,4)' – 2013-03-28 07:22:08

+0

是的,然後好心地更新您的查詢。 – praveen 2013-03-28 07:22:40