Rotate/pivot table with aggregation in Oracle

后端 未结 1 1667
庸人自扰
庸人自扰 2020-12-10 09:47

I\'d like to rotate a table in Oracle 11g. The pivot option requires an aggregation. This is my original table:

project | attribute | value
=================         


        
相关标签:
1条回答
  • 2020-12-10 10:05

    Yes I think so. It is easy to do a pivot like this with a MAX aggregate:

    SELECT
        *
    FROM
    (
        SELECT
            project,
            attribute,
            value
        FROM
            table1
    ) AS SourceTable
    PIVOT
    (
        MAX(value)
        FOR attribute IN ([foo],[bar],[baz])
    ) AS pvt
    

    Otherwise you have to do a case statement inside the a max aggregate. Like this:

    SELECT
        MAX(CASE WHEN attribute='foo' THEN value ELSE NULL END) AS foo,
        MAX(CASE WHEN attribute='bar' THEN value ELSE NULL END) AS bar,
        MAX(CASE WHEN attribute='baz' THEN value ELSE NULL END) AS baz,
        project
    FROM
        table1
    GROUP BY
        project
    

    This is almost the same thing as doing the PIVOT. But I would prefer doing the PIVOT over the CASE WHEN MAX..

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