简体   繁体   中英

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM