在 Oracle 中將多行數據轉換為一行多列可以使用 LISTAGG
函數或者 PIVOT
操作。
LISTAGG
函數:SELECT LISTAGG(column_name, ', ') WITHIN GROUP (ORDER BY column_order) AS concatenated_values
FROM table_name;
例如,將 table_name
中的 column_name
列的多行數據轉換為一行多列數據:
SELECT LISTAGG(column_name, ', ') WITHIN GROUP (ORDER BY column_order) AS concatenated_values
FROM table_name;
PIVOT
操作:SELECT *
FROM (
SELECT column_name, column_value
FROM table_name
)
PIVOT (
MAX(column_value)
FOR column_name IN ('value1' AS value1, 'value2' AS value2, 'value3' AS value3)
);
例如,將 table_name
中的 column_name
列的多行數據轉換為一行多列數據:
SELECT *
FROM (
SELECT column_name, column_value
FROM table_name
)
PIVOT (
MAX(column_value)
FOR column_name IN ('value1' AS value1, 'value2' AS value2, 'value3' AS value3)
);
在以上示例中,根據實際情況修改 table_name
、column_name
和 column_value
等參數即可將多行數據轉換為一行多列數據。