SQL:将行转换为列

时间:2012-02-06 02:33:44

标签: sql oracle pivot

我需要将行的值转换为列 - 例如:

SELECT s.section_name, 
       s.section_value 
  FROM tbl_sections s

此输出:

section_name   section_value
-----------------------------
sectionI       One
sectionII      Two
sectionIII     Three

期望的输出:

sectionI      sectionII      sectionIII
-----------------------------------------
One           Two            Three

1 个答案:

答案 0 :(得分:6)

在您选择的编程语言中,客户端可能做得更好。

您绝对需要事先知道部分名称才能将它们变成列名。

更新了Oracle 11g的答案(使用new PIVOT operator):

SELECT * FROM 
  (SELECT section_name, section_value FROM tbl_sections)
PIVOT
  MAX(section_value) 
    FOR (section_name) IN ('sectionI', 'sectionII', 'sectionIII')

对于旧版本,您可以进行一些自我加入:

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

或者也使用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