-
慕容森
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, 32 2, 4示例:在分组列中使用order by子句进行选择select category, LISTAGG(id, ', ') WITHIN GROUP(ORDER BY id ASC) as idsfrom myTablegroup by category;结果:CATEGORY IDS--------- -----1 1, 3, 52 2, 4
-
临摹微笑
我认为通过这个较小的查询,您可以做您想做的事情。这等效于DB2中MySQL的GROUP_CONCAT。SELECT NUM, SUBSTR(xmlserialize(xmlagg(xmltext(CONCAT( ', ',ROLES))) as VARCHAR(1024)), 3) as ROLESFROM mytable GROUP BY NUM;这将输出类似:NUM ROLES---- -------------1 111, 333, 5552 222, 444假设您的原始结果是这样的:NUM ROLES---- ---------1 1112 2221 3332 4441 555
-
杨魅力
根据您拥有的DB2版本,可以使用XML函数来实现此目的。带有一些数据的示例表create table myTable (id int, category int);insert into myTable values (1, 1);insert into myTable values (2, 2);insert into myTable values (3, 1);insert into myTable values (4, 2);insert into myTable values (5, 1);使用xml函数汇总结果select category, xmlserialize(XMLAGG(XMLELEMENT(NAME "x", id) ) as varchar(1000)) as ids from myTable group by category;结果:CATEGORY IDS -------- ------------------------ 1 <x>1</x><x>3</x><x>5</x> 2 <x>2</x><x>4</x>使用替换使结果看起来更好select category, replace( replace( replace( xmlserialize(XMLAGG(XMLELEMENT(NAME "x", id) ) as varchar(1000)) , '</x><x>', ',') , '<x>', '') , '</x>', '') as ids from myTable group by category;清理结果CATEGORY IDS -------- ----- 1 1,3,5 2 2,4刚看到使用XMLELEMENT的XMLTEXT而不是一个更好的解决方案在这里。