這裏是你所需要的一個完整的例子:
create table #test (
SectionID int,
ItemName varchar(10)
)
insert into #test values (1, 'Item1')
insert into #test values (2, 'Item1')
insert into #test values (1, 'Item2')
insert into #test values (1, 'Item3')
insert into #test values (2, 'Item2')
insert into #test values (3, 'Item1')
insert into #test values (3, 'Item2')
insert into #test values (3, 'Item3')
declare @test int
select @test = 3
declare @dist int
select @dist = count(distinct ItemName) from #test where SectionID = @test
select distinct t0.SectionID from #test t0
left join (select distinct SectionID, ItemName from #test where SectionID = @test) t1
on t0.ItemName = t1.ItemName and t0.SectionID != t1.SectionID
where t0.SectionID != @test
group by t0.SectionID
having count(distinct t1.ItemName) >= @dist
drop table #test
在你的情況,你只需要這一部分:
declare @test int
select @test = 3 --input argument from stored procedure
declare @dist int
select @dist = count(distinct ItemName) from tablename where SectionID = @test
select distinct t0.SectionID from tablename t0
left join (select distinct SectionID, ItemName from tablename where SectionID = @test) t1
on t0.ItemName = t1.ItemName and t0.SectionID != t1.SectionID
where t0.SectionID != @test
group by t0.SectionID
having count(distinct t1.ItemName) >= @dist
我正在格式化我的答案,當你發佈時,它們幾乎完全相同,但我把它放在了上面,因爲看着執行計劃,它看起來更快。 – MyItchyChin 2012-02-01 17:23:36