我有一个正常的选择查询,其结果如下输出。
select cid,x1,x2,x3,x4,fy
from temp_table;
cid x1 x2 x3 x4 fy
----------------------------
6657 100 0 0 200 2014
6658 300 0 0 400 2015
6659 500 0 0 600 2016
我希望它重写它并打印以下输出。
2014 2015 2016
-------------------------
x1 100 300 500
x2 0 0 0
x3 0 0 0
x4 200 400 600
如何才能实现这一目标?
这是一种仅使用子查询和聚合即可实现此目的的方法:
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;
您还可以使用pivot
,但这是 Oracle SQL 的最新补充,因此我倾向于使用此方法。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)