在Oracle中将1条记录拆分为4条记录(将行转置为列)

时间:2019-03-31 15:57:56

标签: sql oracle

我在表中有一条记录,我想根据条件(如果Multirecord = 1)将该记录分为4条记录,并且Q有空值,因此不需要新记录。(如果Q3为空值则不需要第三行) 并插入到新表中。详细信息如下:

表:emp

UID name   is_Multirecord Q1  P1    T1      ....      Q4 P4    T4
1   xyz     1             10  $200 15-03-2019         40 $500  18-03-2019

表EMp_split中的输出

record_no UID  Nae   is_Multi  Q   P     T
1        1      xyz     1      10  $200  15-03-2019
2        1      xyz     1      20  $300   16-03-2019
.....
4.       1      XYZ     1      40   $500  18-03-2019

请帮助。让我知道是否需要其他信息。

1 个答案:

答案 0 :(得分:0)

您可以执行以下操作:

SELECT UID as record_no, name as Nae, is_multirecord as is_Multi, Q1 as Q, P1 as P, T1 as T
WHERE is_multirecord = 1
UNION
SELECT UID as record_no, name as Nae, is_multirecord as is_Multi, Q2 as Q, P2 as P, T2 as T
WHERE is_multirecord = 1
UNION
SELECT UID as record_no, name as Nae, is_multirecord as is_Multi, Q3 as Q, P3 as P, T3 as T
WHERE is_multirecord = 1
UNION
SELECT UID as record_no, name as Nae, is_multirecord as is_Multi, Q4 as Q, P4 as P, T4 as T
WHERE is_multirecord = 1