oracle取消pivot分组

7rfyedvj  于 2021-08-13  发布在  Java
关注(0)|答案(2)|浏览(296)

我正在尝试将列取消pivot到行,以便按我希望在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函数实现?
谢谢

jutyujz0

jutyujz01#

可以按如下方式使用层次结构查询:

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>
46scxncf

46scxncf2#

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

相关问题