-1

I have a junction table in a (SQL Server 2014) database with columns FirstID and SecondID. Given a specific FirstID, I'd like to find all other FirstIDs from the table that have an equivalent set of SecondIDs (even if that set is empty). Sample Data:

FirstId      SecondId
1            1
1            2
2            3
3            1
3            2
...          ...

In the case of the sample data, if I specified FirstID = 1, then I'd expect 3 to appear in the result set.

I've tried the following so far, which works pretty well except for empty sets:

SELECT FirstSecondEqualSet.FirstId
FROM FirstSecond FirstSecondOriginal
INNER JOIN FirstSecond FirstSecondEqualSet ON FirstSecondOriginal.SecondId = FirstSecondEqualSet.SecondId
WHERE FirstSecondOriginal.FirstId = @FirstId 
    AND FirstSecondEqualSet.FirstId != @FirstId
GROUP BY FirstSecondEqualSet.FirstId
HAVING COUNT(1) = (SELECT COUNT(1) FROM FirstSecond WHERE FirstSecond.FirstId = @FirstId)

2 Answers 2

1

I think it's somehow related to Relational Division with no Remainder (RDNR). See this great article by Dwain Camps for reference.

DECLARE @firstId INT = 1

SELECT
    f2.FirstId
FROM FirstSecond f1
INNER JOIN FirstSecond f2 
    ON f2.SecondId = f1.SecondId
    AND f1.FirstId <> f2.FirstId
WHERE
    f1.FirstId = @firstId
GROUP BY f2.FirstId
HAVING COUNT(*) = (SELECT COUNT(*) FROM FirstSecond WHERE FirstId = @firstId)
3
  • Thanks, but this is basically the same thing I wrote in my question (the only difference being that you moved f1.FirstId <> f2.FirstId from the WHERE clause to the JOIN expression, which is interpreted identically by most RDBMS engines).
    – Patrick
    Apr 23, 2015 at 1:51
  • Oh right, I'm sorry. Can you elaborate on the empty set problem? Apr 23, 2015 at 1:53
  • Edited: Nevermind, I just realized the empty set thing makes no sense without domain context, and SO is not really the right venue for that.
    – Patrick
    Apr 23, 2015 at 1:54
1

Here is one approach. It counts the number of values for each firstid and then joins on the secondid.

select fs2.firstid
from (select fs1.*, count(*) over (partition by firstid) as numseconds
      from firstsecond fs1
      where fs1.firstid = @firstid
     ) fs1 join
     (select fs2.*, count(*) over (partition by firstid) as numseconds
      from firstsecond fs2
     ) fs2
     on fs1.secondid = fs2.secondid and fs1.numseconds = fs2.numseconds
group by fs2.firstid
having count(*) = max(fs1.numseconds);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.