Home > Database > Mysql Tutorial > How Can I Create Comma-Separated Lists of Values from Groups in DB2?

How Can I Create Comma-Separated Lists of Values from Groups in DB2?

Linda Hamilton
Release: 2025-01-09 14:36:40
Original
948 people have browsed it

How Can I Create Comma-Separated Lists of Values from Groups in DB2?

Generate comma separated output by group in DB2

DB2 built-in function LISTAGG can concatenate column values ​​with the same grouping, separated by commas. This is useful when you need to merge data within groups.

For example, suppose a table contains two columns, ID and Role, and three rows have the same ID but different Role values. The goal is to concatenate the Role values ​​for each ID into a comma-separated list.

The LISTAGG function introduced starting with DB2 LUW 9.7 accomplishes this:

<code class="language-sql">SELECT ID, LISTAGG(Role, ', ') AS Roles
FROM myTable
GROUP BY ID;</code>
Copy after login

This query will generate the desired output:

<code>ID   Roles
----------
4555 2,3,4</code>
Copy after login
Copy after login

It is worth noting that you can use the WITHIN GROUP clause and the ORDER BY statement to specify the order in which values ​​are concatenated. This allows for greater control over the order in which values ​​are listed:

<code class="language-sql">SELECT ID, LISTAGG(Role, ', ') WITHIN GROUP (ORDER BY Role ASC) AS Roles
FROM myTable
GROUP BY ID;</code>
Copy after login

In this case the output will be:

<code>ID   Roles
----------
4555 2,3,4</code>
Copy after login
Copy after login

LISTAGG Provides a convenient way to aggregate and join data in DB2, enabling efficient group-based string operations.

The above is the detailed content of How Can I Create Comma-Separated Lists of Values from Groups in DB2?. 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