Oracle 11g - 逆透视

2021-12-30 00:00:00 sql oracle11g oracle

我有一张这样的桌子

Date        Year    Month   Day     Turn_1  Turn_2  Turn_3
28/08/2014  2014    08      28      Foo     Bar     Xab

我想以这样的方式旋转"它:

And i would like to "rotate" it in something like this:

Date        Year    Month   Day     Turn    Source
28/08/2014  2014    08      28      Foo     Turn_1
28/08/2014  2014    08      28      Bar     Turn_2
28/08/2014  2014    08      28      Xab     Turn_3  

我需要源"列,因为我需要将此结果连接到另一个表中:

I need the "Source" column because i need to join this results to another table that say:

Source  Interval
Turn_1  08 - 18
Turn_2  11 - 20
Turn_3  18 - 24

现在我使用 unpivot 来旋转表格,但我不知道如何显示源"列(如果可能的话):

For now i have use unpivot to rotate the table, but i dont know how to display the "Source" column (and if it is possible):

select dt_date, df_year, df_month, df_turn
  from my_rotatation_table 
       unpivot( df_turn
                 for x in(turn_1, 
                          turn_2, 
                          turn_3
              ))

已解决:

select dt_date, df_year, df_month, df_turn, df_source
  from my_rotatation_table 
       unpivot( df_turn
                 for df_source in(turn_1 as 'Turn_1', 
                          turn_2 as 'Turn_2', 
                          turn_3 as 'Turn_3'
              ))

推荐答案

使用这个查询:

with t (Dat, Year, Month, Day, Turn_1, Turn_2, Turn_3) as (
  select sysdate, 2014, 08, 28, 'Foo', 'Bar', 'Xab' from dual
)
select dat, year, month, day, turn, source from t
unpivot (
  source  for turn in (Turn_1, Turn_2, Turn_3)
)

DAT         YEAR    MONTH   DAY TURN    SOURCE
----------------------------------------------
08/01/2014  2014    8       28  TURN_1  Foo
08/01/2014  2014    8       28  TURN_2  Bar
08/01/2014  2014    8       28  TURN_3  Xab

相关文章