本文介紹了SQL:將行轉換為列的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
我需要將行的值轉換為列-例如:
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
推薦答案
這可能更好地在客戶端使用您選擇的編程語言完成。
您絕對需要提前知道節(jié)名才能將它們轉換為列名。
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')
對于舊版本,您可以執(zhí)行一些自聯(lián)接:
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技巧和”Aggregate”:
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
這篇關于SQL:將行轉換為列的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,