Aggregating strings
Usually, when we talk about concatenation, we mean putting together values from different columns. A common challenge for database developers is also to concatenate values from multiple rows. This was a task that required writing many lines of code and each developer had a personal implementation.
You can now achieve the same results using the STRING_AGG()
function.
The syntax is:
STRING_AGG(expression, separator) [WITHIN GROUP (ORDER BY expression)]
In this exercise, you will create a list with the origins of the beans for each of the following companies: 'Bar Au Chocolat', 'Chocolate Con Amor', 'East Van Roasters'.
Remember, for STRING_AGG()
to work, you need to find a rule for grouping your data and use it in the GROUP BY
clause.
This exercise is part of the course
Functions for Manipulating Data in SQL Server
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
SELECT
-- Create a list with all bean origins, delimited by comma
___(___, ___) AS bean_origins
FROM ratings
WHERE company IN ('Bar Au Chocolat', 'Chocolate Con Amor', 'East Van Roasters');