How to transpose a table from columns to rows in Oracle sql [duplicate]

不问归期 提交于 2020-01-17 04:33:05

问题


I have a table in sql which has a number of columns with the same type of data each column. I would like to transpose the table's columns into rows so that all of the data appears in 1 column. An example of the type of table I am talking about:

ID    DATE    TEST_1    TEST_2    TEST_3
----------------------------------------
1     1jan12    98        66       77
2     2jan12    75        89       72

Into:

ID    DATE        TEST       SCORE
-----------------------------------
1     1jan12      TEST_1      98
1     1jan12      TEST_2      66
1     1jan12      TEST_3      77
2     2jan12      TEST_1      75
2     2jan12      TEST_2      89
2     2jan12      TEST_3      72

Thanks in advance for any suggestions or directions!


回答1:


One option would be to use 'Union All':

SELECT ID, DATE, 'TEST_1' AS TEST, TEST_1 AS SCORE
FROM TABLE
UNION ALL
SELECT ID, DATE, 'TEST_2' AS TEST, TEST_2 AS SCORE
FROM TABLE
UNION ALL
SELECT ID, DATE, 'TEST_3' AS TEST, TEST_3 AS SCORE
FROM TABLE


来源:https://stackoverflow.com/questions/17060044/how-to-transpose-a-table-from-columns-to-rows-in-oracle-sql

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