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 c ON s.class=c.class
GROUPBY country
ORDERBY country;
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 c ON s.class=c.class
GROUPBY country
ORDERBY country;
country
ships_list
Gt.Britain
Ramillies,Renown,Repulse,Resolution,Revenge,Royal Oak,Royal Sovereign