如何在 Oracle sql 中将表从列转换为行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17060044/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-19 01:43:15  来源:igfitidea点击:

How to transpose a table from columns to rows in Oracle sql

sqloracletranspose

提问by AYR

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:

我在 sql 中有一个表,它有许多列,每列的数据类型相同。我想将表的列转换为行,以便所有数据都出现在 1 列中。我正在谈论的表格类型的一个例子:

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!

在此先感谢您的任何建议或指示!

回答by Sam

One option would be to use 'Union All':

一种选择是使用“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