2012-02-01 132 views
1

我需要寫在T-SQL存儲過程將做到以下幾點:比較兩個select語句

  1. 獲取與某個SectionID
  2. 選擇項的列表,並返回所有SectionID的S作項目或更多的同一列表(不小於)

表結構如下:

Section ID | Item Name 
    1   Item1 
    2   Item1 
    1   Item2 
    1   Item3 
    2   Item2 

所以如果我通過1作爲ID,這不應該返回任何東西SectionID 2只有SectionID = 1有3個項目中的2個,但如果我通過SectionID = 2作爲參數,這應該返回SectionID = 1

希望我解釋清楚。這將是一個好的方法?

回答

3

這裏是你所需要的一個完整的例子:

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 
+0

我正在格式化我的答案,當你發佈時,它們幾乎完全相同,但我把它放在了上面,因爲看着執行計劃,它看起來更快。 – MyItchyChin 2012-02-01 17:23:36

2

假設下面的表...

DECLARE @Sections AS TABLE (Id INT, Item VARCHAR(25)) 

INSERT INTO @Sections 
    (Id, Item) 
    SELECT 1, 'Item1' 
    UNION SELECT 2, 'Item1' 
    UNION SELECT 1, 'Item2' 
    UNION SELECT 1, 'Item3' 
    UNION SELECT 2, 'Item2' 

你可以這樣做...

DECLARE @SectionId INT, @ItemCount INT 

SELECT @SectionId = 2 --You'd change this to whatever 
    , @ItemCount = 0 

SELECT @ItemCount = COUNT(*) 
FROM @Sections 
WHERE Id = @SectionId 

SELECT s.Id 
FROM @Sections AS p 
JOIN @Sections AS s 
    ON s.Id != p.Id 
    AND s.Item = p.Item 
WHERE p.Id = @SectionId 
GROUP BY s.Id 
HAVING COUNT(*) >= @ItemCount