Home > Database > Mysql Tutorial > How to Generate Comma-Separated Values from Grouped Data in DB2 SQL?

How to Generate Comma-Separated Values from Grouped Data in DB2 SQL?

Patricia Arquette
Release: 2025-01-09 14:33:42
Original
694 people have browsed it

How to Generate Comma-Separated Values from Grouped Data in DB2 SQL?

DB2 SQL grouped data generates comma separated values

Question: Is there a function in DB2 SQL that can directly generate comma separated values ​​of grouped column data?

Scenario: We have a table with ID column and Role column. There may be multiple rows for the same ID, with each row representing a different role for that ID. The goal is to concatenate these roles into a comma separated string for each unique ID.

Example:

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

Expected output:

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

Answer:

DB2 LUW 9.7 introduces a new function LITAGG that solves this problem.

Grammar:

<code>LISTAGG(expression, delimiter) WITHIN GROUP (ORDER BY expression ASC|DESC)</code>
Copy after login

Instructions:

  • expression: Column to join
  • delimiter: The delimiter used between concatenated values ​​(e.g.,,)

Usage:

To retrieve the comma separated role values ​​for each unique ID, you can use the following query:

<code>SELECT id, LISTAGG(role, ', ') WITHIN GROUP (ORDER BY role ASC) AS roles
FROM myTable
GROUP BY id;</code>
Copy after login

Output:

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

Additional notes:

  • The ORDER BY clause in the LISTAGG function determines the order of joins.
  • If no ORDER BY clause is specified, the values ​​will be concatenated in any order.
  • The
  • LISTAGG function can also be used to generate other types of connection strings, such as newline-separated values.

The above is the detailed content of How to Generate Comma-Separated Values from Grouped Data in DB2 SQL?. For more information, please follow other related articles on the PHP Chinese website!

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