Home > Database > Mysql Tutorial > Can Oracle SQL Aggregate Multiple Rows into a Single Row?

Can Oracle SQL Aggregate Multiple Rows into a Single Row?

Patricia Arquette
Release: 2025-01-15 18:47:47
Original
886 people have browsed it

Can Oracle SQL Aggregate Multiple Rows into a Single Row?

Oracle SQL: Merge multiple rows of data into one row

Question:

Can Oracle SQL merge multiple rows of data in a table into one row?

Instructions:

Suppose there is a table with the following structure:

<code>A 1
A 2
B 1
B 2</code>
Copy after login

The goal is to get the following result set:

<code>A 1 2
B 1 2</code>
Copy after login

Solution:

Depending on the Oracle SQL version you are using, you can use the following methods:

1. wm_concat() function (Oracle 12c and below):

<code class="language-sql">SELECT field1, wm_concat(field2)
FROM YourTable
GROUP BY field1;</code>
Copy after login

(Note: The wm_concat() function is deprecated in Oracle 12c. It is recommended to use LISTAGG instead.)

2. Custom string aggregation:

If the wm_concat() function is not available, you can implement a custom method to do string aggregation. Please visit oracle-base.com for detailed instructions.

3. Use LISTAGG function (Oracle 11gR2 and above):

This is the recommended modern approach as it is more robust and supported in newer Oracle versions.

<code class="language-sql">SELECT field1, LISTAGG(field2, ' ') WITHIN GROUP (ORDER BY field2) AS aggregated_field2
FROM YourTable
GROUP BY field1;</code>
Copy after login

This query uses the LISTAGG function to concatenate the values ​​in field2 into a string, using spaces as delimiters, and sorting by the value of field2. The WITHIN GROUP (ORDER BY field2) clause ensures the ordering of the values ​​in the resulting string. The GROUP BY field1 clause is grouped according to the value of field1, thereby merging multiple rows into one row.

Choose the solution that best suits your version of Oracle. For Oracle 11gR2 and above, it is strongly recommended to use the LISTAGG function.

The above is the detailed content of Can Oracle SQL Aggregate Multiple Rows into a Single Row?. 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