2010-07-07 59 views
2

噸-SQL SELECT查詢過濾器

Id RelatedId 
-------------- 
1 1 
1 2 
1 3 
2 2 
2 3 
2 4 
3 5 

輸入是@input_1 = 2 and @input_2 = 3(輸入計數可以變化)

我想選擇只從具有上表中這些ID這兩個輸入都在它們對應的RelatedIds中。

因此,基於該給予輸入,輸出將是

Id 
--- 
1 
2 

感謝。

+0

如何通過輸入?這是一個存儲過程嗎?輸入計數可能變化的事實是最棘手的問題。 – 2010-07-07 09:57:13

回答

4

嘗試

select id 
from YourTable 
where relatedid in (@input_1, @input_2) 
group by id 
having count(*) >=2 -- for 3 inputs, make this 3 etc 

例如,你可以運行

create table #yourtable(Id int, RelatedId int) 

insert #yourtable values(1,1) 
insert #yourtable values(1,2) 
insert #yourtable values(1,3) 
insert #yourtable values(2,2) 
insert #yourtable values(2,3) 
insert #yourtable values(2,4) 
insert #yourtable values(3,5) 


declare @input_1 int, @input_2 int 
select @input_1 = 2,@input_2 = 3 

select id 
from #yourtable 
where relatedid in (@input_1, @input_2) 
group by id 
having count(*) >=2 
+0

或者如果有重複的可能性,則記爲「統計(獨特relatedid)」。 – 2010-07-07 10:00:21

1

試試這個:

SELECT Id FROM tableName 
INNER JOIN (SELECT @input_1 AS id 
    UNION SELECT @input_2, 
    UNION SELECT @input_3) inputs 
ON inputs.id = tableName.Id 

Source

或者:

BEGIN 
    DECLARE @inputs TABLE(id tinyint) 
    INSERT INTO @inputs SELECT @input_1 
    INSERT INTO @inputs SELECT @input_2 
    INSERT INTO @inputs SELECT @input_3 

    SELECT * FROM tableName 
    INNER JOIN @inputs i ON i.id = tableName.Id 
END