我有列表,如下所示:
jobnum jobname description oncost
1 abc xxxx cost1
1 abc xxxx cost2
如何在一行中得到如下结果:
jobnum jobname description oncost
1 abc xxxx cost1,Cost2
它实际上取决于特定的数据库,但您需要对行进行分组,并聚合最后一列。下面的查询应该适用于大多数当前数据库:
select jobnum, jobname, description, listagg(oncost,',')
from my_table
group by jobnum, jobname, description
在SQL Server 2017中,您可以使用除string_agg()
之外的所有列的GROUP BY
和oncost
。
SELECT t1.jobnum,
t1.jobname,
t1.description,
string_agg(t1.oncost,
',') oncost
FROM elbat t1
GROUP BY t1.jobnum,
t1.jobname,
t1.description;
对于使用子查询的较低版本,qazxsw poi作为qazxsw poi的替代品是这类问题的典型解决方案。
FOR XML