Pivoting in DB2

The currently accepted answer by bhamby is certainly correct, but it’s worth checking if using several correlated subqueries is much slower than a single group by (hint: it most likely is):

SELECT 
  A.ItemID,
  MAX(CASE WHEN A.Item = 'Meeting'  THEN Value END) AS Meeting,
  MAX(CASE WHEN A.Item = 'Advise'   THEN Value END) AS Advise,
  MAX(CASE WHEN A.Item = 'NoAdvise' THEN Value END) AS NoAdvise
FROM A
GROUP BY A.ItemID

It’s also a bit simpler in my opinion

SQLFiddle (in PostgreSQL, but works on DB2 LUW as well)

Leave a Comment