Pivot / Crosstab Query in Oracle 10g (Dynamic column number)

前端 未结 2 756
伪装坚强ぢ
伪装坚强ぢ 2020-12-15 15:22

I have this table view

UserName      Product     NumberPurchaces
--------      -------     ---------------
\'John Doe\'    \'Chair\'     4
\'John Doe\'    \'         


        
相关标签:
2条回答
  • 2020-12-15 15:47

    I guess one would have to write some code to dynamically create the query. Each MAX() line is identical except for the 'CHAIR', 'TABLE', etc, strings.

    So, one would have to itterate through the data to find all the products and build up a second query as one goes. Then execute that dynamically built query.

    0 讨论(0)
  • 2020-12-15 15:54

    Oracle 11g is the first to support PIVOT/UNPIVOT, so you have to use:

      SELECT t.username,
             MAX(CASE WHEN t.product = 'Chair' THEN t.numberpurchases ELSE NULL END) AS chair,
             MAX(CASE WHEN t.product = 'Table' THEN t.numberpurchases ELSE NULL END) AS tbl,
             MAX(CASE WHEN t.product = 'Bed' THEN t.numberpurchases ELSE NULL END) AS bed
        FROM TABLE t
    GROUP BY t.username
    

    You could use DECODE, but CASE has been supported since 9i.

    0 讨论(0)
提交回复
热议问题