2012-02-01 68 views
0

我有一个ItemList表,其中有一个groupID列和一个itemID列(可以是1,2或3)。我想要做的就是回到这里的组ID具有数据ITEMID的1,2 3.SQL查询帮助 - 按组ID查找

我会用一些示例数据如下说明:

GroupID  ItemID  

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

而且数据I” D喜欢出这将是:

GroupID  ItemID  

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

任何想法我会如何实现这一目标?

感谢

回答

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

这是伟大的福斯科,非常感谢。我知道它一定很容易! – 2012-02-01 17:23:47

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 
) 
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