使用 Oracle SQL 查询进行数据转置
Data transpose using Oracle SQL query
我有 table 和如下数据,
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
请帮忙解决这个问题。
有两件重要的事情需要考虑。
1) SQL table 没有隐含的顺序,所以你必须添加 order by 信息来唯一定义转置的列 table。 (我在table中添加了一个列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" )
)
我有 table 和如下数据,
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
请帮忙解决这个问题。
有两件重要的事情需要考虑。
1) SQL table 没有隐含的顺序,所以你必须添加 order by 信息来唯一定义转置的列 table。 (我在table中添加了一个列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" )
)