1. 程式人生 > >關於oracle LISTAGG函式的用法(以某個欄位相同情況下,將對應的另一個欄位連線起來)

關於oracle LISTAGG函式的用法(以某個欄位相同情況下,將對應的另一個欄位連線起來)

SELECT department_id "Dept.",
       LISTAGG(last_name, '; ') WITHIN GROUP (ORDER BY hire_date) "Employees"
  FROM employees
  GROUP BY department_id
--以上為主功能
  ORDER BY department_id;

Dept. Employees
------ ------------------------------------------------------------
    10 Whalen
    20 Hartstein; Fay
    30 Raphaely; Khoo; Tobias; Baida; Himuro; Colmenares
    40 Mavris
    50 Kaufling; Ladwig; Rajs; Sarchand; Bell; Mallin; Weiss; Davie

department_id相同情況下,將last_name以“;”連線起來,連線時以hire_date排序之後的順序進行combine

在不使用group by的時候可以用over語法代替

SELECT department_id "Dept.",
       LISTAGG(last_name, '; ') WITHIN GROUP (ORDER BY hire_date) "Employees" <span style="background-color: rgb(255, 0, 0);">OVER(PARTITION BY department_id)</span>
  FROM employees

over的用法可以解決一個問題:group by的時候select欄位選擇的時候欄位必須在聚集函式中或者group by欄位中。用over方法可以在select欄位中加任意表中的欄位。