oracle insert 1 row multiple columns 插入多行一列

oracle insert 1 row multiple columns into multiple rows one column

我有一个 table 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

我需要将这些数据插入到另一个 table 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 table 添加一个增量列,如下所示:

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

使用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

使用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<>fiddle here

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'));