比较两个select语句

时间:2012-02-01 16:18:28

标签: sql-server select

我需要在T-SQL中编写一个存储过程,它将执行以下操作:

  1. 获取与某个SectionID
  2. 相关的项目列表
  3. 选择并返回具有相同或更多项目(不少于)的所有SectionID
  4. 表结构如下:

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

    因此,如果我将ID作为1传递,则不应返回任何内容,因为SectionID 2只有SectionID = 1中包含3个项目中的2个,但如果我通过{{1}作为参数,这应该返回SectionID = 2

    希望我能正确解释。对此有什么好处?

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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