基于下表和输入:
Id RelatedId
--------------
1 1
1 2
1 3
2 2
2 3
2 4
3 5
输入为@input_1 = 2 and @input_2 = 3
(输入计数可能不同)
我想只从上表中选择那些在相应的RelatedIds中同时具有这些输入的ID。
因此,根据给定输入,输出将是
Id
---
1
2
感谢。
答案 0 :(得分: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
答案 1 :(得分: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
可替换地:
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