Transpose a query output

后端 未结 4 1491
慢半拍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

    Here is a way to do this with just subqueries and aggregation:

    select name,
           sum(case when fy = 2014 then x end) as "2014",
           sum(case when fy = 2015 then x end) as "2015",
           sum(case when fy = 2016 then x end) as "2016"
    from (select fy,
                 (case when n.n = 1 then 'x1'
                       when n.n = 2 then 'x2'
                       when n.n = 3 then 'x3'
                       when n.n = 4 then 'x4'
                  end) as name,
                 (case when n.n = 1 then x1
                       when n.n = 2 then x2
                       when n.n = 3 then x3
                       when n.n = 4 then x4
                  end) as x
          from temp_table cross join
                (select 1 as n from dual union all
                 select 2 from dual union all
                 select 3 from dual union all
                 select 4 from dual
                ) n
         ) t
    group by name;
    

    You can also use pivot, but that is a very recent addition to Oracle SQL, so I'm inclined to use this method.

提交回复
热议问题