sql - oracle sql中如何将列转换为行
问题描述
我有一个包含以下数据的表格,这里总共有 8 行样本为 3 行 -
现在我使用下面的查询将使用 case 语句的查询转换为这个 -
select
case when entity ='PRODUCT' then prd_table_main end P_main_prd ,
case when entity ='PRODUCT' then prd_table_sec end P_sec_prd,
case when entity ='CUSTOMER' then cus_table_main end P_main_cus ,
case when entity ='CUSTOMER' then cus_table_sec end p_sec_cus,
case when entity ='PROFIT' then prof_table_main end p_main_prof ,
case when entity ='PROFIT' then prof_table_sec end p_sec_prof
from (
select * from above table);
现在我想让 o/p 在一行中删除所有空值。基本上我想创建一个游标并将要在过程中使用的表的值作为 p_main_prd 或 p_sec_prd 或其余表作为要求传递。
解决方案
你快到了,你只需要聚合:
select MAX( case when entity = 'product' then table1 end ) AS P_main_prd,
MAX( case when entity = 'product' then table2 end ) AS P_sec_prd,
MAX( case when entity = 'customer' then table1 end ) AS P_main_cus,
MAX( case when entity = 'customer' then table2 end ) AS p_sec_cus,
MAX( case when entity = 'profit' then table1 end ) AS p_main_prof,
MAX( case when entity = 'profit' then table2 end ) AS p_sec_prof
from table_name;
或使用PIVOT
:
SELECT prd_p_main AS p_main_prd,
prd_p_sec AS p_sec_prd,
cus_p_main AS p_main_cus,
cus_p_sec AS p_sec_cus,
prof_p_main AS p_main_prof,
prof_p_sec AS p_sec_prof
FROM table_name
PIVOT (
MAX( table1 ) AS p_main,
MAX( table2 ) AS p_sec
FOR entity IN (
'product' AS prd,
'customer' AS cus,
'profit' AS prof
)
)
其中,对于样本数据:
CREATE TABLE table_name ( entity, table1, table2 ) AS
SELECT 'product', 'prd_table_main', 'prd_table_sec' FROM DUAL UNION ALL
SELECT 'customer', 'cus_table_main', 'cus_table_sec' FROM DUAL UNION ALL
SELECT 'profit', 'prof_table_main', 'prof_table_sec' FROM DUAL
输出:
P_MAIN_PRD P_SEC_PRD P_MAIN_CUS P_SEC_CUS P_MAIN_PROF P_SEC_PROF prd_table_main prd_table_sec cus_table_main cus_table_sec prof_table_main prof_table_sec
db<>在这里摆弄
推荐阅读
- swift - 滚动时如何一次旋转表格视图单元格中的所有视图?
- python - 如何停止在 django_restframework 中获取重复数据?
- sql-server - 如何删除临时表
- python-3.x - pyinstaller v3.5 执行失败
- char - 字符串索引超出范围,是否有比较两个字符串的正确方法?
- sql - 从主表中获取所有信息,其中子表中的日期字段超过 365 天 - 只是稍微复杂一点
- javascript - 如何比较当前活动标签的 URL
- c# - AS400 锁定未使用的文件
- r - Markdown > html : 将表格标题居中
- css - Google amp-lightbox:内容高于屏幕,无法滚动到顶部