Forum Stats

  • 3,759,066 Users
  • 2,251,495 Discussions
  • 7,870,480 Comments

Discussions

How to get different column names into one column and corresponding values into one column

User_QDHXF
User_QDHXF Member Posts: 20 Green Ribbon
edited Aug 30, 2021 2:30PM in SQL & PL/SQL

Currently, I have a table like:


I need to change it like:


Please let me know what might be the best approach.


Thank You

Tagged:

Best Answer

  • Jan Gorkow
    Jan Gorkow Member Posts: 133 Gold Badge
    Accepted Answer

    Hi @User_QDHXF ,

    this is best done with unpivot:

    SELECT id, category, NVL (VALUE, 0) AS VALUE
     FROM tbl
        UNPIVOT INCLUDE NULLS (VALUE
                   FOR category
                   IN (category1 AS 'Category 1',
                    category2 AS 'Category 2',
                    category3 AS 'Category 3'))
    

    Best regards,

    Jan

    User_QDHXF

Answers