In SQL Server, our task can be solved in a less natural way – by retrieving the result set as XML:
SELECT STUFF(
(SELECT','+name AS'data()'FROM Ships s
JOIN Classes cON s.class=c.classWHERE country='Japan'ORDERBY name FOR XML PATH('')
),1,1,'');
🚫
[[ error ]]
[[ column ]]
NULL
[[ value ]]
Grouping by country will make the query even more complex. Thus, we won’t even attempt to do that, since in SQL Server, beginning with version 2017, there is a function called STRING_AGG that allows concatenating strings. It takes two mandatory arguments – the string expression to be concatenated, and the string separator.
SELECT country, STRING_AGG(name,',') ships_list
FROM Ships s
JOIN Classes cON s.class=c.classGROUPBY country
ORDERBY country;
🚫
[[ error ]]
[[ column ]]
NULL
[[ value ]]
country
ships_list
Gt.Britain
Renown,Repulse,Resolution,Ramillies,Revenge,Royal Oak,Royal Sovereign
Japan
Musashi,Yamato,Haruna,Hiei,Kirishima,Kongo
USA
North Carolina,South Dakota,Washington,Iowa,Missouri,New Jersey,Wisconsin,California,Tennessee
As it can be seen the list of ship names isn’t ordered. GROUP_CONCAT-like sorting doesn’t work here. This can be fixed by using the optional WITHIN GROUP clause:
SELECT country, STRING_AGG(name,',') WITHIN GROUP (ORDERBY name) ships_list
FROM Ships s
JOIN Classes cON s.class=c.classGROUPBY country
ORDERBY country;
🚫
[[ error ]]
[[ column ]]
NULL
[[ value ]]
country
ships_list
Gt.Britain
Ramillies,Renown,Repulse,Resolution,Revenge,Royal Oak,Royal Sovereign