gpt4 book ai didi

sql - DB2 逗号分隔的组输出

转载 作者:行者123 更新时间:2023-12-03 13:08:19 33 4
gpt4 key购买 nike

DB2 SQL 中是否有逗号分隔列值的内置函数? ?

示例:如果有带有 ID 的列它有 3 行相同的 ID但是有三个不同的角色,数据应该用逗号连接。

ID   | Role
------------
4555 | 2
4555 | 3
4555 | 4

每行的输出应如下所示:
4555 2,3,4

最佳答案

LISTAGG 函数是 DB2 LUW 9.7 中的新函数

见示例:

create table myTable (id int, category int);

insert into myTable values (1, 1);
insert into myTable values (2, 2);
insert into myTable values (5, 1);
insert into myTable values (3, 1);
insert into myTable values (4, 2);

示例:在分组列中无任何顺序地选择
select category, LISTAGG(id, ', ') as ids from myTable group by category;

结果:
CATEGORY  IDS
--------- -----
1 1, 5, 3
2 2, 4

示例:在分组列中使用 order by 子句进行选择
select
category,
LISTAGG(id, ', ') WITHIN GROUP(ORDER BY id ASC) as ids
from myTable
group by category;

结果:
CATEGORY  IDS
--------- -----
1 1, 3, 5
2 2, 4

关于sql - DB2 逗号分隔的组输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7188542/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com