0

I have a table like this:

time | ID | Page
9:30 | 1  | name1
9:30 | 1  | name2
9:30 | 1  | name3
9:30 | 2  | name4
9:30 | 2  | name5
7:30 | 3  | name1

And I want to use pivot table to change the table like below:

time | ID | Page1 | Page2 | Page3
9:30 | 1  | name1 | name2 | name3
9:30 | 2  | name4 | name5 | null
7:30 | 3  | name1 | null | null

please help me with that. Thx

2
  • What is the maximum number of pages? up to Page3? Commented Apr 2, 2014 at 15:06
  • Hi, Yes max is up to page3 Commented Apr 2, 2014 at 15:17

1 Answer 1

2

Here you are:

with w(time, ID, Page) as
(
  select '9:30', 1, 'name1' from dual
  union all
  select '9:30', 1, 'name2' from dual
  union all
  select '9:30', 1, 'name3' from dual
  union all
  select '9:30', 2, 'name4' from dual
  union all
  select '9:30', 2, 'name5' from dual
  union all
  select '7:30', 3, 'name1' from dual
)
select *
from
(
  select w.time, w.id, w.page, row_number() over (partition by w.time, w.id order by w.page) rnk
  from w
)
pivot (max(page) for rnk in (1 as page1, 2 as page2, 3 as page3))
order by 1, 2
;

This gives:

TIME    ID    PAGE1    PAGE2    PAGE3
7:30    3     name1        
9:30    1     name1    name2    name3
9:30    2     name4    name5    
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.