Pivoting in DB2

后端 未结 3 490
予麋鹿
予麋鹿 2020-11-29 13:45

I have to transpose my rows into columns from a DB2 table.This is how my table is structured..

ItemID    Item    Value
---------------------
1     Meeting            


        
3条回答
  •  时光说笑
    2020-11-29 14:33

    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)

提交回复
热议问题