Oracle 逆透视分组
Posted
技术标签:
【中文标题】Oracle 逆透视分组【英文标题】:Oracle unpivot grouping 【发布时间】:2020-05-28 12:45:45 【问题描述】:我正在尝试将列取消透视到行,以便它们按我希望在 unpivot 函数中构造的单位编号进行分组
为简化解释,请参见下面的示例查询:
select
'123456789' student
,'01/Jul/2020' unit_1_date
,'Mathematics 'unit_1_subject
,'01/Aug/2020' unit_2_date
,'English 'unit_2_subject
from
dual
输出五列:
student unit_1_date unit_1_subject unit_2_date unit_2_subject
123456789 01/Jul/2020 Mathematics 01/Aug/2020 English
我希望取消透视这些列,以便它们可以按单元号分组并显示如下:
student unit_number unit_date unit_subject
123456789 1 01/Jul/2020 Mathematics
123456789 2 01/Aug/2020 English
我已尝试使用 unpivot 函数来执行此操作,如下所示:
select * from
(select
'123456789' student
,'01/Jul/2020' unit_1_date
,'Mathematics 'unit_1_subject
,'01/Aug/2020' unit_2_date
,'English 'unit_2_subject
from
dual) units
unpivot(unit_date for unit_number in(
unit_1_subject as '1',
unit_1_date as '1',
unit_2_subject as '2',
unit_2_date as '2'
))
输出日期如下:
Student Unit number Unit_date
123456789 1 Mathematics
123456789 1 01/Jul/2020
123456789 2 English
123456789 2 01/Aug/2020
我不确定如何对其中的两列进行分组,以便它们按单元号分组。最好的方法是什么?这可以通过 UNPIVOT 功能实现吗?
谢谢
【问题讨论】:
【参考方案1】:您可以按如下方式使用层次结构查询:
SQL> SELECT
2 STUDENT,
3 LEVEL AS UNIT,
4 CASE WHEN LEVEL = 1 THEN UNIT_1_DATE ELSE UNIT_2_DATE END AS UNIT_DATE,
5 CASE WHEN LEVEL = 1 THEN UNIT_1_SUBJECT ELSE UNIT_2_SUBJECT END AS SUBJECT
6 FROM
7 ( SELECT
8 '123456789' STUDENT,
9 '01/Jul/2020' UNIT_1_DATE,
10 'Mathematics ' UNIT_1_SUBJECT,
11 '01/Aug/2020' UNIT_2_DATE,
12 'English ' UNIT_2_SUBJECT
13 FROM DUAL
14 ) CONNECT BY LEVEL <= 2;
STUDENT UNIT UNIT_DATE SUBJECT
--------- ---------- ----------- ------------
123456789 1 01/Jul/2020 Mathematics
123456789 2 01/Aug/2020 English
SQL>
【讨论】:
【参考方案2】:你可以使用union all
:
select
student,
1 unit_number,
unit_1_date unit_date,
unit_1_date,
unit_1_subject
from mytable
union all
select
student,
2 unit_number,
unit_2_date unit_date,
unit_2_date,
unit_2_subject
from mytable
【讨论】:
以上是关于Oracle 逆透视分组的主要内容,如果未能解决你的问题,请参考以下文章
《MSSQL2008技术内幕:T-SQL语言基础》读书笔记(下)
图像透视基于matlab图像逆透视映射含Matlab源码 2139期
图像透视基于matlab图像逆透视映射含Matlab源码 2139期