Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

sql - Oracle 11g - Unpivot

I have a table like this

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

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
              ))

SOLVED:

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'
              ))
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Use this query:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...