Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2005 Forums
 Transact-SQL (2005)
 Comparing subset of two tables

Author  Topic 

nathans
Aged Yak Warrior

938 Posts

Posted - 2007-09-05 : 14:56:31
Guys,
The following works, but seems like overkill to me. Am I missing some simple left join setup??


declare @xref table (GroupID int, ItemID int)
insert into @xref
select 1, 1 union
select 1, 2 union
select 1, 3 union
select 2, 4 union
select 2, 5

declare @in table (GroupID int, ItemID int)
insert into @in
select 1, 3 union
select 2, 1 union
select 2, 5

-- For GroupID = 1 should return ItemIDs (1, 2)
-- for GroupID = 2 should return ItemIDs (4)


select distinct d.*
from ( select * from @xref
except
select * from @in
)d
join @in i on
d.GroupID = i.GroupID


-- desired results:

GroupID ItemID
----------- -----------
1 1
1 2
2 4





SwePeso
Patron Saint of Lost Yaks

30421 Posts

Posted - 2007-09-05 : 15:20:34
This only will do
select * from @xref
except
select * from @in



E 12°55'05.25"
N 56°04'39.16"
Go to Top of Page

jen
Master Smack Fu Yak Hacker

4110 Posts

Posted - 2007-09-05 : 15:33:13
select groupid,itemid
from (
select groupid,itemid
from @xref
union all
select groupid, itemid
from @in
) s
group by groupid,itemid
having count(*)=1

or

select groupid,itemid
from @xref
except
select x.groupid,x.item from @xref x join @in i
on x.groupid=i.groupid and x.itemid=i.itemid

--------------------
keeping it simple...
Go to Top of Page

nathans
Aged Yak Warrior

938 Posts

Posted - 2007-09-05 : 15:38:16
quote:
Originally posted by Peso

This only will do
select * from @xref
except
select * from @in



E 12°55'05.25"
N 56°04'39.16"



I should have stated it more clearly... For the following test data it should only return the GroupID = 1 subset:

declare @in table (GroupID int, ItemID int)
insert into @in
select 1, 3

-- desired resultset:

GroupID ItemID
----------- -----------
1 1
1 2

Go to Top of Page
   

- Advertisement -