sql - 无法使用 ; 将行数据转置为列 在甲骨文中分离
问题描述
请您说明一下我如何转置以下数据。
Create Table Pivot (Empname VARCHAR (10),
Deptno varchar(10),
Salary number (10));
Insert into Pivot (Empname, Deptno, Salary) values ('Max', '10',1000);
Insert into Pivot (Empname, Deptno, Salary) values ('David', '20',2000);
Insert into Pivot (Empname, Deptno, Salary) values ('AD', '30',3000);
所以选择查询的输出将是
EMPNAME DEPTNO SALARY
MAX 10 1000
David 20 2000
AD 30 3000
现在我们需要数据的所需格式如下:
Empname Max David Ad
Deptno 10 20 30
Sal 1000 2000 3000
请分享您对此的看法。
解决方案
一种选择是使用Conditional Aggregation
with UNION ALL
:
select 'Deptno' as "Empname",
max( case when Empname = 'Max' then to_number(Deptno) end ) as "Max",
max( case when Empname = 'David' then to_number(Deptno) end ) as "David",
max( case when Empname = 'AD' then to_number(Deptno) end ) as "AD"
from pivot
union all
select 'Sal',
max( case when Empname = 'Max' then Salary end ) ,
max( case when Empname = 'David' then Salary end ) ,
max( case when Empname = 'AD' then Salary end )
from pivot;
或另一种选择是使用pivot
子句UNION ALL
:
select 'Deptno' as "Empname", max("Max") as "Max", max("David") as "David", max("AD") as "AD"
from pivot
pivot( max(to_number(Deptno)) for Empname in ('Max' as "Max",'David' as "David",'AD' as "AD"))
union all
select 'Sal', max("Max") as "Max", max("David") as "David", max("AD") as "AD"
from pivot
pivot( max(Salary) for Empname in ('Max' as "Max",'David' as "David",'AD' as "AD"));
推荐阅读
- rest - 无论如何我们可以使用vsphere rest api访问用户的权限和角色吗?
- .htaccess - 我们如何在 .php 文件本身或 htaccess 中添加具有多个 .php 变量的 URL?
- sql - 我有 2 个不同的表,例如 user 和 user_managers,我需要根据 userid 获取经理详细信息
- batch-file - 如何将信息从批处理文件 1 发送到批处理文件 2?
- php - 来自数组的图形表示逻辑
- java - 我应该先从 Jon 和他的朋友那里得到副本吗?还是只获取值而不获取重复项?
- python - 配置不当的异常,但它仍然有效
- react-native - 如何使用 Expo React-Native 检测抖动事件?
- python - 使用 pyscopg2 将不同长度的行插入 Postgres
- cmake - 在 CMake 中设置 Clang 库的路径