SQL查询帮助 - 按groupID查找

时间:2012-02-01 15:57:12

标签: sql-server

我有一个ItemList表,其中有一个groupID列和一个itemID列(可以是1,2或3)。我想要做的是返回groupID具有itemID为1,2 AND 3的数据。

我将在下面举例说明一些示例数据:

GroupID       ItemID       

   1            1       
   2            1 
   2            2 
   2            3
   3            1
   3            2 
   4            1
   4            2
   4            3
   5            1
   5            2

我想要的数据是:

GroupID       ItemID       

   2            1 
   2            2 
   2            3
   4            1
   4            2
   4            3

我是如何实现这一目标的?

由于

3 个答案:

答案 0 :(得分:2)

您可以使用EXISTS()查询来检查条件,如下所示:

select i.GroupID, i.ItemID
from ItemList i
where 
exists (select 1 from ItemList where GroupID = i.GroupID and ItemID = 1)
and exists (select 1 from ItemList where GroupID = i.GroupID and ItemID = 2)
and exists (select 1 from ItemList where GroupID = i.GroupID and ItemID = 3)
order by i.GroupID, i.ItemID

答案 1 :(得分:0)

declare @T table
(
  GroupID int,
  ItemID int
)
insert into @T values       
(   1,            1),       
(   2,            1), 
(   2,            2),
(   2,            3),
(   3,            1),
(   3,            2), 
(   4,            1),
(   4,            2),
(   4,            3),
(   5,            1),
(   5,            2)

select GroupID, ItemID
from @T 
where GroupID in
  (
    select GroupID
    from @T
    group by GroupID
    having count(distinct ItemID) = 3
  )

答案 2 :(得分:0)

使用JOIN的替代方案(虽然我没有为性能找借口)但它有效; - )

SELECT IL1.*
FROM ItemList IL1
INNER JOIN (SELECT GroupID FROM ItemList WHERE ItemID = 1) IL2
ON IL2.GroupID = IL1.GroupID
INNER JOIN (SELECT GroupID FROM ItemList WHERE ItemID = 2) IL3
ON IL3.GroupID = IL1.GroupID
INNER JOIN (SELECT GroupID FROM ItemList WHERE ItemID = 3) IL4
ON IL4.GroupID = IL1.GroupID