在Oracle中,group_concat
函數并不是一個內置的函數,但你可以使用LISTAGG
函數來實現類似的功能
以下是一個示例,說明如何使用LISTAGG
函數處理空值:
SELECT department_id, LISTAGG(employee_name, ',') WITHIN GROUP (ORDER BY employee_name) AS employees
FROM (
SELECT department_id, employee_name,
ROW_NUMBER() OVER (PARTITION BY department_id ORDER BY employee_name) AS rn
FROM employees
WHERE employee_name IS NOT NULL -- 過濾掉空值
)
GROUP BY department_id;
在這個示例中,我們首先使用子查詢過濾掉employee_name
為空的記錄。然后,我們使用LISTAGG
函數將每個部門的員工名字連接成一個字符串。最后,我們按照部門ID進行分組。
注意:在使用LISTAGG
函數時,如果結果字符串超過4000字節,你需要使用CAST
函數將結果轉換為CLOB類型。例如:
SELECT department_id, CAST(COLLECT(employee_name) AS CLOB) AS employees
FROM (
SELECT department_id, employee_name,
ROW_NUMBER() OVER (PARTITION BY department_id ORDER BY employee_name) AS rn
FROM employees
WHERE employee_name IS NOT NULL -- 過濾掉空值
)
GROUP BY department_id;
這里,我們使用CAST
函數將LISTAGG
函數的結果轉換為CLOB類型。