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
-----------------------
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