Home > Database > Mysql Tutorial > How Can I Create Comma-Separated Lists of Column Values in DB2 Using LISTAGG?

How Can I Create Comma-Separated Lists of Column Values in DB2 Using LISTAGG?

Linda Hamilton
Release: 2025-01-09 14:46:42
Original
884 people have browsed it

How Can I Create Comma-Separated Lists of Column Values in DB2 Using LISTAGG?

Generating Comma-Separated Lists in DB2 SQL Using LISTAGG

The DB2 LISTAGG function simplifies the creation of comma-separated lists of column values, particularly when dealing with grouped data. This function efficiently concatenates values from a specified column for rows sharing the same grouping criteria, using a custom delimiter.

Let's illustrate with a table containing ID and Role columns, where an ID might have multiple associated Role values. To generate a comma-separated list of roles for each unique ID, use this SQL query:

<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

Example Data:

<code>ID   | Role
------------
4555 | 2
4555 | 3
4555 | 4</code>
Copy after login

Result:

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

The ORDER BY clause within LISTAGG controls the order of concatenated values. ORDER BY Role ASC arranges them ascendingly; ORDER BY Role DESC would arrange them descendingly. Omitting ORDER BY results in an undefined order.

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