Home >Database >Mysql Tutorial >How Can I Ensure Distinct Values When Using Oracle's LISTAGG Function?

How Can I Ensure Distinct Values When Using Oracle's LISTAGG Function?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2025-01-19 18:26:09123browse

How Can I Ensure Distinct Values When Using Oracle's LISTAGG Function?

Oracle LISTAGG: Generating Strings with Unique Values

Oracle's LISTAGG function is invaluable for concatenating column values into a single string. However, obtaining only distinct values within the aggregated string requires a specific approach. This guide demonstrates efficient methods, avoiding the need for custom functions or stored procedures.

Oracle 19c and Later: Leveraging DISTINCT Directly

For Oracle 19c and subsequent versions, the DISTINCT keyword can be seamlessly integrated within the LISTAGG function itself:

<code class="language-sql">SELECT LISTAGG(DISTINCT the_column, ',') WITHIN GROUP (ORDER BY the_column)
FROM the_table;</code>

Oracle 18c and Earlier: Employing a Subquery

In older Oracle versions (18c and earlier), a subquery is necessary to filter for unique values before aggregation:

<code class="language-sql">SELECT LISTAGG(the_column, ',') WITHIN GROUP (ORDER BY the_column)
FROM (
    SELECT DISTINCT the_column
    FROM the_table
) t;</code>

Incorporating Multiple Columns

The following query extends the functionality to include multiple columns, demonstrating a robust method for more complex scenarios:

<code class="language-sql">SELECT DISTINCT col1, listagg(col2, ',') OVER (PARTITION BY col1 ORDER BY col2) AS col2_list
FROM table_name
WHERE RN = 1
GROUP BY col1
ORDER BY col1;</code>

In conclusion, using either the DISTINCT keyword (19c and above) or a subquery (18c and below), you can effectively generate LISTAGG results containing only unique values. These techniques offer flexibility across different Oracle versions and facilitate the inclusion of multiple columns when required.

The above is the detailed content of How Can I Ensure Distinct Values When Using Oracle's LISTAGG Function?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn