Transpose a query output

后端 未结 4 1440
慢半拍i
慢半拍i 2021-01-17 05:26

I have a normal select query which results following output.

select cid,x1,x2,x3,x4,fy
  from temp_table;

cid     x1  x2  x3  x4  fy
-----------------------         


        
4条回答
  •  礼貌的吻别
    2021-01-17 06:09

    More general solution is with UNPIVOT and PIVOT.
    Your temp_table is already a pivot table with (x1 x2 x3 x4) as x-axis and fy as y-axis.
    First we need to UNPIVOT temp_table into unpivoted_temp_table and then PIVOT it with fy as x-axis and (x1 x2 x3 x4) as y-axis:

    with unpivoted_temp_table as (
    
    SELECT *
      FROM   temp_table
      UNPIVOT (
              totalSales                            
              FOR x                             
              IN  (x1, x2, x3, x4)
             )
    )  
    
    select *  
    FROM   unpivoted_temp_table 
      PIVOT (
                   SUM(totalSales)        
               FOR fy          
              IN (2014, 2015, 2016)
             )
    order by 1 --order by column X
    

    http://sqlfiddle.com/#!4/4fdfc/1/0

提交回复
热议问题