SQL:将单行拆分为2行或3行

时间:2017-03-06 15:04:52

标签: sql unpivot

我希望将一行分成2行或3行。这可能吗?
我有一个表格,显示这样的引号:

表名:引号

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

但我想要显示这样的引号:

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

我猜我需要使用某种UNION来做这件事,但我不知所措。我对SQL比较陌生,希望有人能指出我正确的方向。

最近的我(也不是非常接近)是这样做的:

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

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:1)

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

where子句删除没有成本的行,例如TaxiCost为空时。使用union all代替union:后者删除重复的行。