--gustavo_gonzalez_tsqlchallenge_22.sql
DECLARE @result TABLE(BallId INT, BoxId INT);
DECLARE @total INT;
SET @total = 1;
WHILE (@total > 0)
BEGIN
INSERT INTO @result
SELECT
p.BallId, MIN(p.BoxId)
FROM
TC22_Preferences p
WHERE
NOT EXISTS (SELECT 1 FROM @result WHERE NOT(BallId <> p.BallId AND BoxId <> p.BoxId))
GROUP BY
p.BallId
HAVING COUNT(DISTINCT p.BoxId) = 1
UNION
SELECT
MIN(p.BallId), p.BoxId
FROM
TC22_Preferences p
WHERE
NOT EXISTS (SELECT 1 FROM @result WHERE NOT(BallId <> p.BallId AND BoxId <> p.BoxId))
GROUP BY
p.BoxId
HAVING COUNT(DISTINCT p.BallId) = 1
;
SET @total = @@ROWCOUNT;
END
SELECT
BoxName Box
, BallName Ball
FROM
@result t
JOIN TC22_Boxes a ON t.BoxId = a.BoxId
JOIN TC22_Balls b ON t.BallId = b.BallId
ORDER BY
t.BoxId
Did you find something incorrect/wrong with this solution? Take a few seconds to Report It.
Did you understand how this solution work? If you find it difficult to understand, you can Request an Explanation or you can Write an explanation to help others better understand this solution.