Comma separated results in SQL

后端 未结 5 1167
我寻月下人不归
我寻月下人不归 2020-11-22 03:24

I have the following code which will create a comma delimited list for my results:

DECLARE @listStr VARCHAR(MAX)
SELECT @listStr = COALESCE(@listStr+\', \' ,         


        
5条回答
  •  感情败类
    2020-11-22 03:45

    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;
    

提交回复
热议问题