Home > Database > Mysql Tutorial > How Can I Remove Duplicates When Using Oracle's LISTAGG Function?

How Can I Remove Duplicates When Using Oracle's LISTAGG Function?

Barbara Streisand
Release: 2025-01-19 18:12:11
Original
595 people have browsed it

How Can I Remove Duplicates When Using Oracle's LISTAGG Function?

Oracle LISTAGG: Handling Duplicate Values for Unique Results

Oracle's LISTAGG function, while powerful for aggregating data, doesn't inherently remove duplicate entries. It concatenates all values, including repetitions, into a single string. Here's how to achieve distinct value aggregation:

Method for Oracle 19c and Later:

Oracle 19c and later versions offer a simplified solution:

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

This directly incorporates the DISTINCT keyword within the LISTAGG function itself.

Method for Oracle 18c and Earlier:

For older versions (18c and below), a subquery is necessary:

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

This first selects only the unique values in a subquery, then applies LISTAGG to that result.

Including Multiple Columns:

To include additional columns and maintain uniqueness, a more advanced approach is required:

<code class="language-sql">SELECT col1, LISTAGG(col2, ',') WITHIN GROUP (ORDER BY col2)
FROM (
  SELECT col1, 
         col2,
         ROW_NUMBER() OVER (PARTITION BY col1, col2 ORDER BY col1) AS rn
  FROM foo
  ORDER BY col1, col2
)
WHERE rn = 1
GROUP BY col1;</code>
Copy after login

This uses ROW_NUMBER() to assign a unique rank to each combination of col1 and col2. The outer query then selects only the first occurrence (rn = 1) for each unique combination, ensuring that duplicates are eliminated before aggregation.

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

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template