Search code examples
plsqlunpivot

How to Unpivot this table?


Base table

I have been trying out unpivot but to no avail. My desired output should be: Desired output


Solution

    • First, you need to unpivot your intial data in order to get rows per month and per another new column containing values for both columns A and B.
    • Then, you can easily pivot the resulting data to get the desired output format.
    WITH Your_test_cases (MONTH, a, b) AS (
    SELECT 
      to_char(add_months(TRUNC(SYSDATE, 'YEAR'), LEVEL - 1), 'FMMONTH', 'nls_date_language=ENGLISH') MONTH
    , LEVEL a
    , LEVEL b
    FROM dual
    CONNECT BY LEVEL <= 12
    )
    SELECT *
    FROM Your_test_cases
    UNPIVOT (
    VAL_A_AND_B_IN_ONE_COL FOR COL IN (
      A AS 'A'
    , B AS 'B'
    )
    )
    PIVOT (
    MIN(VAL_A_AND_B_IN_ONE_COL) FOR MONTH IN (
    'JANUARY' as JANUARY,
    'FEBRUARY' as FEBRUARY,
    'MARCH' as MARCH,
    'APRIL' as APRIL,
    'MAY' as MAY,
    'JUNE' as JUNE,
    'JULY' as JULY,
    'AUGUST' as AUGUST,
    'SEPTEMBER' as SEPTEMBER,
    'OCTOBER' as OCTOBER,
    'NOVEMBER' as NOVEMBER,
    'DECEMBER' as DECEMBER
    )
    )
    ORDER BY 1
    ;
    

    demo