2012-02-01 165 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