2010-07-07 58 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