I am using DB2 and have the following table (Table A – 3 Columns) :
EmpNum YearMonth Value
100 201201 2
100 201207 1
100 201206 7
102 201201 8
102 201205 15
102 201207 4
… etc
I would like to produce a new Table B with one row per employee, and a column for each YearMonth.
I am hoping that I can generate the Table B ‘YearMonth’ column name dynamically from the data as there will be 120 columns.
The value would then be put in the cell with the associated YearMonth heading to give a table like this :
EmpNum 201201 201202 201203 201204 201205 201206 201207 etc ….
100 2 7 1
102 8 15 4
I have tried looking up ‘Stored Procedures’ and ‘Dynamic Column Names’ but cannot fine anything quite like this.
I have two questions :
- Is this possible in DB2 ?
- What should I look up for more information ?
Thanks in anticipation !
Ross
What you are looking for is called Pivot. Unfortunately, DB2 doesn’t implement the PIVOT statement (unlike Oracle). So it will not be possible to create a query that creates a dynamic number of columns.
Have a look at Poor Man's SQL Pivot. List Questions as Columns and Answers per User in one row. That’s the closest you can get to.