Search code examples
sqlunpivot

SQL: Split a single row into 2 or 3 rows


I'm looking to split a row into 2 or 3 rows. Is this possible?
I have a table that shows quotes like this:

TABLE NAME: Quotes

ID | NAME  | BusCost | TaxiCost | TrainCost 
-------------------------------------------
01 | Steve | NULL    | 25       | NULL
02 | Barry | 15      | 30       | NULL
03 | Bob   | 150     | 400      | 300

But I want to show the quotes like this:

ID | Name   | Cost
------------------
01 | Steve  | 25
02 | Barry  | 15
02 | Barry  | 30
03 | Bob    | 30
03 | Bob    | 100
03 | Bob    | 70

I am guessing I am going to need to use some kind of UNION to do this but I'm at a loss. I'm relatively new to SQL and was hoping if anyone can point in me in the right direction.

The closest I've come (not very close either) is by doing this:

SELECT COST
FROM 
(
SELECT BusCost AS COST FROM Quotes
UNION
SELECT TaxiCost AS COST FROM Quotes
UNION
SELECT TrainCost AS COST FROM Quotes
) A
GROUP BY COST

SELECT id, name FROM Quotes
UNION ALL
SELECT COST
FROM
(
SELECT BusCost AS COST FROM Quotes
UNION
SELECT TaxiCost AS COST FROM Quotes
UNION
SELECT TrainCost AS COST FROM Quotes
) A
GROUP BY COST

Any help would be greatly appreciated.


Solution

  • SELECT  *
    FROM    (
            SELECT  id
            ,       Name
            ,       BusCost as Cost
            FROM    Quotes
            UNION ALL
            SELECT  id
            ,       Name
            ,       TaxiCost
            FROM    Quotes
            UNION ALL
            SELECT  id
            ,       Name
            ,       TrainCost
            FROM    Quotes
            ) AllCosts
    WHERE   Cost IS NOT NULL
    

    The where clause removes rows that have no cost, for example when TaxiCost is empty. Use union all instead of union: the later removes duplicate rows.