How can I Pivot a table in DB2?

   select Id,                                              
      max(case when Code = '1' then Value end) as Code1_Val,  
      max(case when Code = '2' then Value end) as Code2_Val,  
      max(case when Code = '3' then Value end) as Code3_Val   
      from TABLEA                                     
      group by Id                                            

If your version doesn't have DECODE(), you can also use this:

INSERT INTO B (id, code1_val, code2_val, code3_val)  
WITH Ids (id) as (SELECT DISTINCT id
                  FROM A) -- Only to construct list of ids

SELECT Ids.id, a1.value, a2.value, a3.value
FROM Ids -- or substitute the actual id table
JOIN A a1
     ON a1.id = ids.id
        AND a1.code = 1
JOIN A a2
     ON a2.id = ids.id
        AND a2.code = 2
JOIN A a3
     ON a3.id = ids.id
        AND a3.code = 3

(Works on my V6R1 DB2 instance, and have an SQL Fiddle Example).


SELECT Id,
max(DECODE(Code, 1, Value)) AS Code1_Val,
max(DECODE(Code, 2, Value)) AS Code2_Val,
max(DECODE(Code, 3, Value)) AS Code3_Val
FROM A
group by Id

Tags:

Sql

Db2