Convert rows to columns oracle SQL

2019-03-02 20:12发布

I did not find any suitable previous answers hence posting the question. I need to convert rows to columns. The PIVOT examples all convert the rows to a single column whereas my requirement is multiple columns. My table looks like this

Type     ID
test1    10
test1    20
test1    30
test2    10
test2    40

I would like it to be

Type       ID        Type      ID
test1      10       test2      10
test1      20       test2      40
test1      30

Appreciate your suggestions/inputs!

标签: oracle pivot
2条回答
forever°为你锁心
2楼-- · 2019-03-02 20:29

You could enumerate rows with row_number() and make pivot:

SQLFiddle demo

select * 
  from (
    select d.*, row_number() over(partition by type order by id) rn from data d)
  pivot (max(type) type, max(id) id for type in ('test1' t1, 'test2' t2))
查看更多
一纸荒年 Trace。
3楼-- · 2019-03-02 20:54

If the 'ID' column is the primarykey you can only have one column as primarykey in the table.

查看更多
登录 后发表回答