我有下面的表格和数据,
Create table transpose (a number, b number, c number);
insert into transpose values (1,4,7);
insert into transpose values (2,5,8);
insert into transpose values (3,6,9);
commit;
select * from transpose;
A B C
1 4 7
2 5 8
3 6 9
问题:我需要使用sql查询下面的输出,这是否可能 反转数据(转置数据)?
A B C
1 2 3
4 5 6
7 8 9
请帮忙解决此问题。
答案 0 :(得分:0)
有两件重要的事情需要考虑。
1)SQL表没有隐含的顺序,因此您必须添加 order by 信息以唯一地定义转置表的列。 (我在表格中添加了一个列ID来模拟它。)
2)如果您正在寻找固定数量的列和行的解决方案,您可以在SQL查询中对结果进行编码,如下所示(对于动态解决方案,我不建议使用SQL)
select
(select a from transpose where id = 1) a,
(select a from transpose where id = 2) b,
(select a from transpose where id = 3) c
from dual
union all
select
(select b from transpose where id = 1) a,
(select b from transpose where id = 2) b,
(select b from transpose where id = 3) c
from dual
union all
select
(select c from transpose where id = 1) a,
(select c from transpose where id = 2) b,
(select c from transpose where id = 3) c
from dual;
A B C
---------- ---------- ----------
1 2 3
4 5 6
7 8 9
更新 - 使用PIVOT的解决方案
正如@WW在这里提出的带有数据透视的解决方案
with trans as (
/* add one select for each column */
select id, 'A' col_name, a col_value from transpose union all
select id, 'B' col, b col_value from transpose union all
select id, 'C' col, b col_value from transpose)
select * from trans
PIVOT (sum(col_value) col_value
for (id) in
(1 as "C1", /* add one entry for each row (ID) */
2 as "C2",
3 as "C3" )
)