Home » SQL & PL/SQL » SQL & PL/SQL » PIVOTING: one row to multiple columns
PIVOTING: one row to multiple columns [message #636813] |
Sun, 03 May 2015 16:55 |
|
dancko
Messages: 108 Registered: June 2013 Location: italy
|
Senior Member |
|
|
Hi to all,
I'm not expert with pivoting operation/function and I have to transpose each row of a source table in many columns of a target table.
Here an example:
Source Table
Name_1, Name_2, Surname_1, Surname_2
n1, n2, s1, s2
n3, n4, s3, s4
Target Table
Name, Surname
n1, s1
n2, s2
n3, s3
n4, s4
Can any one help me to realize this requirements?
Thanks in advance.
[Updated on: Sun, 03 May 2015 16:59] Report message to a moderator
|
|
|
|
|
|
|
|
|
|
Re: PIVOTING: one row to multiple columns [message #636830 is a reply to message #636827] |
Mon, 04 May 2015 03:35 |
|
dancko
Messages: 108 Registered: June 2013 Location: italy
|
Senior Member |
|
|
Hi, Michel Cadot
Source Table:
CREATE TABLE PIVOT_SRC
(
NAME_1 VARCHAR2(4000 BYTE),
NAME_2 VARCHAR2(4000 BYTE),
SURNAME_1 VARCHAR2(4000 BYTE),
SURNAME_2 VARCHAR2(4000 BYTE)
)
INSERT INTO PIVOT_SRC VALUES('n1','n2','c1','c2');
INSERT INTO PIVOT_SRC VALUES('n3','n4','c3','c4');
Target Table:
CREATE TABLE PIVOT_TGT
(
NAME VARCHAR2(4000 BYTE),
SURNAME VARCHAR2(4000 BYTE)
)
Desidered Result in target table PIVOT_TGT:
Name, Surname
n1, s1
n2, s2
n3, s3
n4, s4
[Updated on: Mon, 04 May 2015 03:35] Report message to a moderator
|
|
|
Re: PIVOTING: one row to multiple columns [message #636831 is a reply to message #636830] |
Mon, 04 May 2015 03:47 |
|
Michel Cadot
Messages: 68648 Registered: March 2007 Location: Nanterre, France, http://...
|
Senior Member Account Moderator |
|
|
SQL> col name format a10
SQL> col surname format a10
SQL> with
2 row_gen as ( -- as many lines as you want to split the rows
3 select level line from dual connect by level <= 2
4 )
5 select decode(line, 1, name_1, 2, name_2) name,
6 decode(line, 1, surname_1, 2, surname_2) surname
7 from pivot_src, row_gen
8 /
NAME SURNAME
---------- ----------
n1 c1
n3 c3
n2 c2
n4 c4
4 rows selected.
|
|
|
Re: PIVOTING: one row to multiple columns [message #636832 is a reply to message #636830] |
Mon, 04 May 2015 04:10 |
Lalit Kumar B
Messages: 3174 Registered: May 2013 Location: World Wide on the Web
|
Senior Member |
|
|
Another way:
SQL> col name format a10
SQL> col surname format a10
SQL> WITH DATA AS(
2 SELECT name_1||','||name_2 text1, surname_1||','||surname_2 text2 FROM PIVOT_SRC
3 )
4 SELECT
5 trim(regexp_substr(t.text1, '[^,]+', 1, lines.COLUMN_VALUE)) name,
6 trim(regexp_substr(t.text2, '[^,]+', 1, lines.COLUMN_VALUE)) surname
7 FROM DATA t,
8 TABLE (CAST (MULTISET
9 (SELECT LEVEL FROM dual CONNECT BY LEVEL <= regexp_count(t.text1, ',')+1)
10 AS sys.odciNumberList
11 )
12 ) lines
13 /
NAME SURNAME
---------- ----------
n1 c1
n2 c2
n3 c3
n4 c4
SQL>
Note : I haven't tested the performance of the query.
|
|
|
|
|
|
Goto Forum:
Current Time: Wed May 08 00:28:42 CDT 2024
|