我需要将行的值转换为列 - 例如:
SELECT s.section_name,
s.section_value
FROM tbl_sections s
Run Code Online (Sandbox Code Playgroud)
这个输出:
section_name section_value
-----------------------------
sectionI One
sectionII Two
sectionIII Three
Run Code Online (Sandbox Code Playgroud)
期望的输出:
sectionI sectionII sectionIII
-----------------------------------------
One Two Three
Run Code Online (Sandbox Code Playgroud)
在您选择的编程语言中,客户端可能做得更好.
您绝对需要事先知道节名称才能将它们转换为列名.
更新了Oracle 11g的答案(使用新的PIVOT运算符):
SELECT * FROM
(SELECT section_name, section_value FROM tbl_sections)
PIVOT
MAX(section_value)
FOR (section_name) IN ('sectionI', 'sectionII', 'sectionIII')
Run Code Online (Sandbox Code Playgroud)
对于旧版本,您可以执行一些自联接:
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
Run Code Online (Sandbox Code Playgroud)
或者也使用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
Run Code Online (Sandbox Code Playgroud)