1) i assume that you don't have duplicate id
2) get the key with the same number of value
3) the row with the number of key value equal to the number of equal value is the target
I hope it's what you searched for (you don't search performance don't you ?)
declare @a table( pkid int, value int)
declare @b table( otherID int, value int)
insert into @a values (1, 1000)
insert into @a values (1, 1001)
insert into @a values (2, 1000)
insert into @a values (2, 1001)
insert into @a values (2, 1002)
insert into @a values (3, 1000)
insert into @a values (3, 1001)
insert into @a values (4, 1000)
insert into @a values (4, 1001)
insert into @b values (-1, 1000)
insert into @b values (-1, 1001)
insert into @b values (-1, 1002)
insert into @b values (-2, 1001)
insert into @b values (-2, 1002)
insert into @b values (-3, 1000)
insert into @b values (-3, 1001)
select cntok.cntid1 as cntid1, cntok.cntid2 as cntid2
from
(select cnt.cnt, cnt.cntid1, cnt.cntid2 from
(select acnt.cnt as cnt, acnt.cntid as cntid1, bcnt.cntid as cntid2 from
(select count(pkid) as cnt, pkid as cntid from @a group by pkid)
as acnt
full join
(select count(otherID) as cnt, otherID as cntid from @b group by otherID)
as bcnt
on acnt.cnt = bcnt.cnt)
as cnt
where cntid1 is not null and cntid2 is not null)
as cntok
inner join
(select count(1) as cnt, cnta.cntid1 as cntid1, cnta.cntid2 as cntid2
from
(select cnt, cntid1, cntid2, a.value as value1
from
(select cnt.cnt, cnt.cntid1, cnt.cntid2 from
(select acnt.cnt as cnt, acnt.cntid as cntid1, bcnt.cntid as cntid2 from
(select count(pkid) as cnt, pkid as cntid from @a group by pkid)
as acnt
full join
(select count(otherID) as cnt, otherID as cntid from @b group by otherID)
as bcnt
on acnt.cnt = bcnt.cnt)
as cnt
where cntid1 is not null and cntid2 is not null)
as cntok
inner join @a as a on a.pkid = cntok.cntid1)
as cnta
inner join
(select cnt, cntid1, cntid2, b.value as value2
from
(select cnt.cnt, cnt.cntid1, cnt.cntid2 from
(select acnt.cnt as cnt, acnt.cntid as cntid1, bcnt.cntid as cntid2 from
(select count(pkid) as cnt, pkid as cntid from @a group by pkid)
as acnt
full join
(select count(otherID) as cnt, otherID as cntid from @b group by otherID)
as bcnt
on acnt.cnt = bcnt.cnt)
as cnt
where cntid1 is not null and cntid2 is not null)
as cntok
inner join @b as b on b.otherid = cntok.cntid2)
as cntb
on cnta.cntid1 = cntb.cntid1 and cnta.cntid2 = cntb.cntid2 and cnta.value1 = cntb.value2
group by cnta.cntid1, cnta.cntid2)
as cntequals
on cntok.cnt = cntequals.cnt and cntok.cntid1 = cntequals.cntid1 and cntok.cntid2 = cntequals.cntid2