来自 SQL 聚合查询的逗号分隔结果

Comma separated result from SQL query with aggregate

请原谅我对 SQL 查询的了解不足。我有两个表 -

并且,

我需要一个查询来产生如下所示的输出 -

可能吗?

注意:(在您将其标记为重复之前)-我已经看到很多关于 SO 的其他问题需要为更简单的场景显示逗号分隔的结果,但我认为这一个有点不同,因为 Artist 上的分组和 TotalSale 上的聚合。

简单。

-- Your sample data
declare @artist table (id int, name varchar(10));
insert @artist values (1,'A'),(2,'B');

declare @album table (id int, artistId int, name varchar(10), sold int);
insert @album values (1,1,'P',2), (2,1,'Q',3), (3,2,'X',1), (4,2,'Y',3),(5,2,'Z',2);

--solution
select 
  artist    = ar.name,
  totalSale = sum(al.sold),
  albums    = stuff(max(concatAlbums.albumList),1,1,'')
from @artist ar
join @album al on ar.id = al.artistId
cross apply   
(
    select ','+name
    from @album al2
    where al2.artistId  = ar.id
    for xml path('')
) concatAlbums(albumList)
group by ar.name;

结果:

artist     totalSale   albums
---------- ----------- -------
A          5           P,Q
B          6           X,Y,Z