2015-01-14 346 views
1

,我有以下數據:拆分一行到多行基於列的值DB2

Sr no....EMP_ID....Location...Period1....Value1....Period2....Value2....Period3....Value3 
...1......Emp001....India........Salary.....10000.....Bonus.....1000.......Bonus code...AB 
...2......Emp002....UK...........Salary.....20000.....Bonus.....2000.......Bonus code...CD 

我想要的輸出是這樣的:

Sr no....EMP_ID....Location....Period...Value 
....1......Emp001....India.......Salary.....10000 
....2......Emp001....India.......Bonus.....1000 
....3......Emp001....India.......Bonus Code.....AB 
....4......Emp002....UK.......Salary.....20000 
....5......Emp002....UK.......Bonus.....2000 
....6......Emp002....UK.......Bonus Code.....CD 
+0

您正在使用哪個數據庫,MySQL或DB2?你應該相應地標記你的問題。 –

回答

2

這是一個逆轉置操作。你可以做你想做一個什麼union all

select EmpNo, Location, Period1 as period, Value1 as Value 
from data 
union all 
select EmpNo, Location, Period2 as period, Value2 as Value 
from data 
union all 
select EmpNo, Location, Period3 as period, Value3 as Value 
from data; 

有些數據庫有unpivot的直接支持,以及其他的方法做。但是,以上是ANSI標準SQL。

+0

它與OP的預期輸出的唯一區別是'Sr no'。 –

+0

如果我有成千上萬的員工..? – HunTer

+1

然後你會得到成千上萬的行。對於成千上萬行,「union all」應該是相當有效的。 –