Using pivot on multiple columns of an Oracle row(在 Oracle 行的多个列上使用数据透视)
问题描述
I have the following sample data in an Oracle table (tab1
) and I am trying to convert rows to columns. I know how to use Oracle pivot on one column. But is it possible to apply it to multiple columns?
Sample data:
Type weight height
A 50 10
A 60 12
B 40 8
C 30 15
My intended output:
A-count B-count C-count A-weight B-weight C-weight A-height B-height C-height
2 1 1 110 40 30 22 8 15
What I can do:
with T AS
(select type, weight from tab1 )
select * from T
PIVOT (
count(type)
for type in (A, B, C, D,E,F)
)
The above query gives me the below result
A B C
2 1 1
I can replace count(*)
with sum(weight)
or sum(height)
to pivot height or weight. What I am looking to do, but I can't do, is pivot on all three (count, weight and height) in one query.
Can it be done using pivot?
As the documentation shows, you can have multiple aggregate function clauses. So you can do this:
select * from (
select * from tab1
)
pivot (
count(type) as ct, sum(weight) as wt, sum(height) as ht
for type in ('A' as A, 'B' as B, 'C' as C)
);
A_CT A_WT A_HT B_CT B_WT B_HT C_CT C_WT C_HT
---- ---- ---- ---- ---- ---- ---- ---- ----
2 110 22 1 40 8 1 30 15
If you want the columns in the order you showed then add another level of subquery:
select a_ct, b_ct, c_ct, a_wt, b_wt, c_wt, a_ht, b_ht, c_ht
from (
select * from (
select * from tab1
)
pivot (
count(type) as ct, sum(weight) as wt, sum(height) as ht
for type in ('A' as A, 'B' as B, 'C' as C)
)
);
A_CT B_CT C_CT A_WT B_WT C_WT A_HT B_HT C_HT
---- ---- ---- ---- ---- ---- ---- ---- ----
2 1 1 110 40 30 22 8 15
SQL Fiddle.
这篇关于在 Oracle 行的多个列上使用数据透视的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 Oracle 行的多个列上使用数据透视


- SQL 临时表问题 2022-01-01
- 导入具有可变标题的 Excel 文件 2021-01-01
- 在SQL中,如何为每个组选择前2行 2021-01-01
- 如何使用 pip 安装 Python MySQLdb 模块? 2021-01-01
- 使用 Oracle PL/SQL developer 生成测试数据 2021-01-01
- 如何将 Byte[] 插入 SQL Server VARBINARY 列 2021-01-01
- 更改自动增量起始编号? 2021-01-01
- 如何将 SonarQube 6.7 从 MySQL 迁移到 postgresql 2022-01-01
- 以一个值为轴心,但将一行上的数据按另一行分组? 2022-01-01
- 远程 mySQL 连接抛出“无法使用旧的不安全身份验证连接到 MySQL 4.1+"来自 XAMPP 的错误 2022-01-01