oracle将1行多列插入多行一列

时间:2019-06-25 11:14:36

标签: sql oracle unpivot

我有一个表t1,其中包含以下内容:(数百万行)

ID    ID_1    ID_2   ID_3   ID_4
---------------------------------
1      10      11     12     13
2      14      15     16     17
3      18      19     20     21

我需要将这些数据插入另一个表t2中,如下所示:

ID     ID_X
------------
1       10
1       11
1       12
1       13
2       14
2       15
2       16
2       17
3       18
3       19
3       20
3       21

我已经使用LOOP和游标完成了我需要的操作,但是我需要通过一次插入操作来实现更好的性能。

有什么想法吗?

编辑:

通过回复,我实现了使用UNPIVOT所需的功能。

现在,我需要进一步向t2表中添加一个增量列,如下所示:

ID     ID_X     ID_Y
----------------------
1       10       0
1       11      200
1       12      400
1       13      600
2       14       0
2       15      200
2       16      400
2       17      600
3       18       0
3       19      200
3       20      400
3       21      600

3 个答案:

答案 0 :(得分:1)

使用UNPIVOT

Oracle设置

CREATE TABLE t1 ( ID, ID_1, ID_2, ID_3, ID_4 ) AS
  SELECT 1, 10, 11, 12, 13 FROM DUAL UNION ALL
  SELECT 2, 14, 15, 16, 17 FROM DUAL UNION ALL
  SELECT 3, 18, 19, 20, 21 FROM DUAL;

CREATE TABLE t2 ( ID NUMBER, ID_X NUMBER );

插入声明

INSERT INTO t2 (id, id_x )
  SELECT id, value
  FROM   t1
  UNPIVOT ( value FOR name IN ( ID_1, ID_2, ID_3, ID_4 ) );

输出

SELECT * FROM t2;
ID | ID_X
-: | ---:
 1 |   10
 1 |   11
 1 |   12
 1 |   13
 2 |   14
 2 |   15
 2 |   16
 2 |   17
 3 |   18
 3 |   19
 3 |   20
 3 |   21

db <>提琴here

答案 1 :(得分:0)

使用UNION可以实现。以下查询将起作用:

INSERT INTO Newtable (ID, ID_X) 
SELECT ID, ID_X FROM (
    SELECT ID, ID_1 AS ID_X FROM TableName UNION
    SELECT ID, ID_2 AS ID_X FROM TableName UNION
    SELECT ID, ID_3 AS ID_X FROM TableName UNION  
    SELECT ID, ID_4 AS ID_X FROM TableName
) A
ORDER BY ID, ID_X

答案 2 :(得分:0)

select ID, ID_X from test unpivot(ID_X for value in (ID_1 as 'A', ID_2 as 'B',ID_3 as 'C',ID_4 as 'D'));