Advanced SQL: Using Pivot

365 Days of Daily Coding: Day 121

I felt a little sick today cause last night I did not get quality sleep. I ate a spicy meal for my dinner and I had a burning sensation in my stomach in the early morning so I am sleep deprived as well. I realised that this is one of the puzzle that I have solved in the past already so it was an easy one.

Puzzle 5: Phone Directory

I tried to come up with a solution using the live oracle sql environment here.

My solution:

WITH temp AS (
Select 10001 AS CustomerID, 'Cellular'  AS Type, '555-897-5421' AS PhoneNumber FROM Dual Union All
Select 10001 AS CustomerID, 'Work'      AS Type, '555-897-6542' AS PhoneNumber FROM Dual Union All
Select 10001 AS CustomerID, 'Home'      AS Type, '555-698-9874' AS PhoneNumber FROM  Dual Union All
Select 20002 AS CustomerID, 'Cellular'  AS Type, '555-963-6544' AS PhoneNumber FROM Dual Union All
Select 20002 AS CustomerID, 'Work'      AS Type, '555-812-9856' AS PhoneNumber FROM Dual Union All
Select 30003 AS CustomerID, 'Cellular'  AS Type, '555-987-6541' AS PhoneNumber FROM Dual
)

SELECT * FROM
(
  SELECT CustomerID, Type, PhoneNumber
  FROM temp
)
PIVOT 
(
  MIN(PhoneNumber)
  FOR Type
  IN ('Cellular' AS Cellular, 'Work' AS Work, 'Home' AS Home) )
Order BY CustomerID ASC;

Leave a comment