oracle SQL:将行转换为列
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9155033/
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
SQL : Turning rows into columns
提问by Ianthe
I need to turning the value of a row into column - for example:
我需要将行的值转换为列 - 例如:
SELECT s.section_name,
s.section_value
FROM tbl_sections s
this outputs :
这输出:
section_name section_value
-----------------------------
sectionI One
sectionII Two
sectionIII Three
desired output :
所需的输出:
sectionI sectionII sectionIII
-----------------------------------------
One Two Three
回答by Thilo
This is probably better done client-side in the programming language of your choice.
这可能在您选择的编程语言中在客户端完成得更好。
You absolutely need to know the section names in advance to turn them into column names.
您绝对需要提前知道部分名称才能将它们转换为列名称。
Updated answer for Oracle 11g (using the new PIVOT operator):
Oracle 11g 的更新答案(使用新的 PIVOT 运算符):
SELECT * FROM
(SELECT section_name, section_value FROM tbl_sections)
PIVOT
MAX(section_value)
FOR (section_name) IN ('sectionI', 'sectionII', 'sectionIII')
For older versions, you could do some self-joins:
对于旧版本,您可以进行一些自联接:
WITH
SELECT section_name, section_value FROM tbl_sections
AS
data
SELECT
one.section_value 'sectionI',
two.section_value 'sectionII',
three.section_value 'sectionIII'
FROM
select selection_value from data where section_name = 'sectionI' one
CROSS JOIN
select selection_value from data where section_name = 'sectionII' two
CROSS JOIN
select selection_value from data where section_name = 'sectionIII' three
or also use the MAX trick and "aggregate":
或者也使用 MAX 技巧和“聚合”:
SELECT
MAX(DECODE(section_name, 'sectionI', section_value, '')) 'sectionI',
MAX(DECODE(section_name, 'sectionII', section_value, '')) 'sectionII',
MAX(DECODE(section_name, 'sectionIII', section_value, '')) 'sectionIII'
FROM tbl_sections