Search code examples
sqloracle-databaseoracle11gunpivot

Turn the table columns as rows


I have the table with the following structure. I need to turn columns as rows

ID  NAME      2011   2012
1   macbook   2      241
2   macbook   77     214
3   macbook   0      400
4   iphone    442    555

with tbl as (
 select  1 as id, 'macbook' as name, 2 as "2011", 241 as "2012" from dual union
 select  2 as id, 'macbook' as name, 77 as "2011", 214 as "2012" from dual union
 select  3 as id, 'macbook' as name, 0 as "2011", 400 as "2012" from dual union
 select  4 as id, 'iphone' as name, 442 as "2011", 555 as "2012" from dual
)
select * from tbl

I use Oracle database, I tried to solve the issue by using unpivot function but I stacked on this

I expect to get the result like this

ID  NAME    DATE    SALES
1   macbook 2011    2
1   macbook 2012    241
2   macbook 2011    77
2   macbook 2012    214
3   macbook 2011    0
3   macbook 2012    400
4   iphone  2011    442
4   iphone  2012    555

Solution

  • Try This : Using unpivot

    with tbl as (
     select  1 as id, 'macbook' as name, 2 as "2011", 241 as "2012" from dual union
     select  2 as id, 'macbook' as name, 77 as "2011", 214 as "2012" from dual union
     select  3 as id, 'macbook' as name, 0 as "2011", 400 as "2012" from dual union
     select  4 as id, 'iphone' as name, 442 as "2011", 555 as "2012" from dual
    )
    select * from tbl
    UNPIVOT (SALES FOR "DATE" IN ("2011" AS '2011', "2012" AS '2012'));
    

    OUTPUT :

    enter image description here