STRING_AGG function
Text data aggregation
Let’s consider the following task.
List the names of all Japanese vessels in the Ships table in a single line, separated by commas.
There is no problem getting the list of Japanese ships:
[[ column ]] |
---|
NULL
[[ value ]] |
In MySQL, there is the remarkable GROUP_CONCAT aggregate function that provides the solution to this task:
[[ column ]] |
---|
NULL
[[ value ]] |
ships_list |
---|
haruna,hiei,kirishima,kon,musashi,yamato |
By default, the comma is used as a list separator; however, we can choose any symbol.
Grouping makes it easy to obtain a ship list for each country:
[[ column ]] |
---|
NULL
[[ value ]] |
country | ships_list |
---|
gt.britain | renown,repulse,resolution,ramillies,revenge,royal oak,royal sovereign |
japan | haruna,hiei,kirishima,kongo,musashi,yamato |
usa | iowa,missouri,new jersey,wisconsin,north carolina,south dakota,washington,california,tennessee |
In SQL Server, our task can be solved in a less natural way – by retrieving the result set as XML:
[[ 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.
[[ 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:
[[ column ]] |
---|
NULL
[[ value ]] |
country | ships_list |
---|
Gt.Britain | Ramillies,Renown,Repulse,Resolution,Revenge,Royal Oak,Royal Sovereign |
Japan | Haruna,Hiei,Kirishima,Kongo,Musashi,Yamato |
USA | California,Iowa,Missouri,New Jersey,North Carolina,South Dakota,Tennessee,Washington,Wisconsin |
Suggested exercises: 139