如何将1条记录分成多条记录?

时间:2018-02-13 03:01:48

标签: sql

我想使用SQL将1条记录分成多条记录

原始表:

+---------+------+------+------+
| orderid | qty1 | qty2 | qty3 |
+---------+------+------+------+
| 1234    | 5    | 6    | 7    |
+---------+------+------+------+

我想分成:

+---------+------+------+------+
| orderid | qty1 | qty2 | qty3 |
+---------+------+------+------+
| 1234    | 5    |      |      |
+---------+------+------+------+
| 1234    |      | 6    |      |
+---------+------+------+------+
| 1234    |      |      | 7    |
+---------+------+------+------+

如何做到这一点,请帮助我,谢谢!

2 个答案:

答案 0 :(得分:1)

您可以尝试这样的事情

SELECT orderid , qty1 ,NULL, NULL FROM  Order_Tbl  
UNION ALL
SELECT orderid , NULL, qty2, NULL  FROM  Order_Tbl  
UNION ALL
SELECT orderid , NULL ,NULL, qty3 FROM  Order_Tbl 

答案 1 :(得分:1)

SQL的一些方言支持显式横向连接。否则,如果您关心性能,可以使用cross join。像这样:

select t.orderid,
       (case when n.n = 1 then qty1 end) as qty1,
       (case when n.n = 2 then qty2 end) as qty2,
       (case when n.n = 3 then qty3 end) as qty3
from t cross join
     (select 1 as n union all select 2 as n union all select 3 as n) n;

更常见的是,在拆分这样的数据时,您可能希望单个列中的所有值,可能还有另一列指定原始列:

select t.orderid, n.n,
       (case when n.n = 1 then qty1
             when n.n = 2 then qty2
             when n.n = 3 then qty3
        end) as qty
from t cross join
     (select 1 as n union all select 2 as n union all select 3 as n) n;