📜  oracle sql listagg - SQL (1)

📅  最后修改于: 2023-12-03 15:03:23.943000             🧑  作者: Mango

Oracle SQL Listagg - SQL

In Oracle SQL, the LISTAGG function is used to concatenate non-NULL values from a column into a single string. The resulting string can be used for report generation, creating comma-separated lists, and other operational needs.

Syntax

The syntax for the LISTAGG function is as follows:

LISTAGG (expression, separator) WITHIN GROUP (ORDER BY expression)
  • expression: This is the column or expression whose values will be concatenated.
  • separator: This is the delimiter used to separate the concatenated values.
  • ORDER BY expression: This is an optional parameter used to order the concatenated values.
Example

Consider the following EMPLOYEES table:

EMPLOYEE_ID   NAME           DEPARTMENT
---------------------------------------
1             John Doe       Sales
2             Jane Smith     Marketing
3             Bob Johnson    Sales
4             Mark Johnson   Marketing
5             Sarah Lee      HR

To concatenate the names of all employees in each department, we can use the following query:

SELECT DEPARTMENT, LISTAGG(NAME, ', ') FROM EMPLOYEES GROUP BY DEPARTMENT;

The result of this query will be:

DEPARTMENT   LISTAGG(NAME,',')
-------------------------------
Sales        John Doe, Bob Johnson
Marketing    Jane Smith, Mark Johnson
HR           Sarah Lee

In this example, the , separator is used to separate the concatenated values.

Conclusion

The LISTAGG function in Oracle SQL is a powerful tool for concatenating values from a column into a single string. It is useful for a variety of operational needs, such as report generation and creating comma-separated lists. The function is easy to use and provides a lot of flexibility through its parameters.