0
我有一個要求來旋轉從用戶指定的特定表的列。 問題是從每個表中透視的列數是動態的。 所以下面的代碼獲取表中列的名稱。在SQL中使用嵌套select時無法正常工作
SELECT DISTINCT
LISTAGG('''' || column_name || '''', ',')
WITHIN GROUP (ORDER BY column_name) AS temp_in_statement
FROM (SELECT DISTINCT column_name FROM all_tab_columns WHERE table_name = 'DIM_XYZ')
上面的代碼返回以下列格式中的列:
col1, col2
我必須使用樞軸這一要求並且爲了樞轉列在下面的代碼插上面的代碼。
SELECT * FROM
(
SELECT table_name, column_name
FROM ALL_TAB_COLUMNS
WHERE
table_name = 'DIM_XYZ'
)
PIVOT
(
MIN(column_name)
FOR column_name IN (
-- values added manually
'col1','col2'
-- values added manually
)
)
ORDER BY table_name;
的代碼工作正常,在這種情況下,但更換時 'COL1', 'COL2' 由SELECT語句檢索的列名的系統引發以下錯誤:
ORA-00936: missing expression
00936. 00000 - "missing expression"
*Cause:
*Action:
Error at Line: 39 Column: 40
CODE:
SELECT * FROM
(
SELECT table_name, column_name
FROM ALL_TAB_COLUMNS
WHERE
table_name = 'DIM_XYZ'
)
PIVOT
(
MIN(column_name)
FOR column_name IN (
--code below does not work when plugged in the statement above
SELECT DISTINCT
LISTAGG('''' || column_name || '''', ',')
WITHIN GROUP (ORDER BY column_name) AS temp_in_statement
FROM (SELECT DISTINCT column_name FROM all_tab_columns WHERE table_name = 'DIM_XYZ')
--code above does not work
)
)
ORDER BY table_name;
----------------
你們有什麼想法如何解決這個問題嗎?
listagg返回的STRING(單數)可能看起來像你在IN()中使用的東西,但事實是它不能以這種方式工作。您需要創建「動態sql」以將單個字符串「'col1','col2'」解釋爲一對字符串'col1','col2'。 –