maephisto
maephisto

Reputation: 5182

Oracle split row

I have a legacy table whos data I have to migrate to a new structure. In the old structure each row represesnts an year, having fields for each month. In the new one each row will represent a month. The old structure is :

OLD_TABLE (
id1,
id2,
    year,
price01,
price02,
price03,
price04,
...
price11,
price12,
quantity01,
quantity02,
quantity03,
...
quantity11,
quantity12,

) -> PK = id1,id2,year

the new structure is like this :

NEW_TABLE (
id1,
id2,
year,
month,
quantity,
price,

) -> PK = id1,id2, year

Any advices on how should i proceed in migrating data from the old structure to the new one?

Thank you!

Upvotes: 1

Views: 312

Answers (2)

schurik
schurik

Reputation: 7928

SELECT id1, id2, year, 1 as month, quantity01 as quantity, price01 as price FROM old_table
UNION ALL
SELECT id1, id2, year, 2 as month, quantity02 as quantity, price02 as price FROM old_table
UNION ALL
SELECT id1, id2, year, 3 as month, quantity03 as quantity, price03 as price FROM old_table
UNION ALL
SELECT id1, id2, year, 4 as month, quantity04 as quantity, price04 as price FROM old_table
UNION ALL
SELECT id1, id2, year, 5 as month, quantity05 as quantity, price05 as price FROM old_table
UNION ALL
SELECT id1, id2, year, 6 as month, quantity06 as quantity, price06 as price FROM old_table
UNION ALL
SELECT id1, id2, year, 7 as month, quantity07 as quantity, price07 as price FROM old_table
UNION ALL
SELECT id1, id2, year, 8 as month, quantity08 as quantity, price08 as price FROM old_table
UNION ALL
SELECT id1, id2, year, 9 as month, quantity09 as quantity, price09 as price FROM old_table
UNION ALL
SELECT id1, id2, year, 10 as month, quantity010 as quantity, price010 as price FROM old_table
UNION ALL
SELECT id1, id2, year, 11 as month, quantity011 as quantity, price011 as price FROM old_table
UNION ALL
SELECT id1, id2, year, 12 as month, quantity012 as quantity, price012 as price FROM old_table
;

Upvotes: 1

podiluska
podiluska

Reputation: 51494

If you are using 11g or later, look at the unpivot syntax

Something like...

SELECT *
FROM yourtable
UNPIVOT (price FOR pmonth IN (price01 AS 1, price02 AS 2...))
UNPIVOT (quantity FOR qmonth IN (quantity01 AS 1, quantity02 AS 2...))
WHERE pmonth=qmonth

Upvotes: 3

Related Questions