Convert rows to columns oracle SQL

Deadly 提交于 2019-12-31 04:08: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!


回答1:


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



回答2:


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



来源:https://stackoverflow.com/questions/31481060/convert-rows-to-columns-oracle-sql

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!