Comma separated results in SQL
For Sql Server 2017 and later you can use the new STRING_AGG
function
https://docs.microsoft.com/en-us/sql/t-sql/functions/string-agg-transact-sql
The following example replaces null values with 'N/A' and returns the names separated by commas in a single result cell.
SELECT STRING_AGG ( ISNULL(FirstName,'N/A'), ',') AS csv FROM Person.Person;
Here is the result set.
John,N/A,Mike,Peter,N/A,N/A,Alice,Bob
Perhaps a more common use case is to group together and then aggregate, just like you would with SUM
, COUNT
or AVG
.
SELECT a.articleId, title, STRING_AGG (tag, ',') AS tags
FROM dbo.Article AS a
LEFT JOIN dbo.ArticleTag AS t
ON a.ArticleId = t.ArticleId
GROUP BY a.articleId, title;
this works in sql server 2016
USE AdventureWorks
GO
DECLARE @listStr VARCHAR(MAX)
SELECT @listStr = COALESCE(@listStr+',' ,'') + Name
FROM Production.Product
SELECT @listStr
GO
Update (As suggested by @Aaron in the comment)
STRING_AGG is the preferred way of doing this in the modern versions of SQL Server.
Original Answer:
Use FOR XML PATH('')
- which is converting the entries to a comma separated string and STUFF() -which is to trim the first comma- as follows Which gives you the same comma separated result
SELECT STUFF((SELECT ',' + INSTITUTIONNAME
FROM EDUCATION EE
WHERE EE.STUDENTNUMBER=E.STUDENTNUMBER
ORDER BY sortOrder
FOR XML PATH(''), TYPE).value('text()[1]','nvarchar(max)')
, 1, LEN(','), '') AS listStr
FROM EDUCATION E
GROUP BY E.STUDENTNUMBER
Here is the FIDDLE