Advanced SQL Puzzle: Using JOINS

365 Days of Daily Coding Challenge: Day 90

It’s D-90, exactly 3 months since I started my daily coding challenge journey. I feel extremely humbled knowing that I have many more milestones to achieve although I am better than I was in D-1.

To embrace my vulnerability when most if not everybody only display their best foot forward, I admit that there were days where I completely lacked the motivation to complete a daily challenge. I have learned to accept it. Most important of all, I have learned to rebound and refocus on my goals.

I have also finally managed to finalise a topic for my dataviz project and I am currently in the midst of collecting data. It’s a topic that sits closer to my heart and the project will channel my passion for it. Please do stay tuned.

Advanced SQL Challenge:

WITH temp As (
Select 1001 As CustomerID, 'Class A' AS Part FROM Dual Union All
Select 1001 As CustomerID, 'Class B' AS Part FROM Dual Union All
Select 1001 As CustomerID, 'Class C' AS Part FROM Dual Union All
Select 2002 As CustomerID, 'Class A' AS Part FROM Dual Union All
Select 2002 As CustomerID, 'Class B' AS Part FROM Dual Union All
Select 2002 As CustomerID, 'Class C' AS Part FROM Dual Union All
Select 3003 As CustomerID, 'Class A' AS Part FROM Dual Union All
Select 3003 As CustomerID, 'Class D' AS Part FROM Dual 
), temp2 AS (
SELECT CustomerID, Part1 || Part2 || Part3 AS unq
FROM(
SELECT t1.CustomerID , t1.Part AS Part1, t2.Part AS Part2, t3.Part AS Part3
FROM temp t1 JOIN temp t2 
ON t1.CustomerID = t2.CustomerID 
JOIN temp t3
ON t2.CustomerId = t3.CustomerId
WHERE t1.Part <> t2.Part AND t3.Part <> t2.Part AND t1.Part <> t3.Part))

SELECT DISTINCT l1.CustomerID, l2.CustomerID FROM temp2 l1 JOIN temp2 l2
ON l1.unq = l2.unq
WHERE l1.CustomerID <> l2.CustomerID;

Leave a comment