Split a row into multiple rows based on a column value db2

我怕爱的太早我们不能终老 提交于 2019-12-11 10:36:42

问题


I have the following data:

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

I want the output like this :

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

回答1:


This is an unpivot operation. You can do what you want with a 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;

Some databases have direct support for unpivot as well as other methods for doing it. However, the above is ANSI standard SQL.



来源:https://stackoverflow.com/questions/27942097/split-a-row-into-multiple-rows-based-on-a-column-value-db2

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!