Oracle 逆透视分组

Oracle unpivot grouping

我正在尝试将列逆透视为行,以便按我希望在逆透视函数中构建的单位编号对它们进行分组

为了简化说明,请参阅下面的示例查询:

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 函数实现吗?

谢谢

你可以直接使用 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

您可以使用层级查询如下:

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>