2012-08-13 61 views
1

我有一个遗留表whos数据,我必须迁移到一个新的结构。在旧的结构中,每一行代表一年,每个月都有一个字段。在新的每一行将代表一个月。旧的结构是:Oracle拆分行

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

) - > PK = ID1,ID2,一年

新的结构是这样的:

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

) - > PK = ID1,ID2,一年

关于如何继续将数据从旧结构迁移到新结构的任何建议?

谢谢!

回答

3

如果您使用11g或以上版本,看看unpivot语法

喜欢的东西...

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 
+0

感谢,这真是棒极了! – maephisto 2012-08-13 08:30:24

1
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 
;