Comma separated results in SQL

后端 未结 5 1228
我寻月下人不归
我寻月下人不归 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:41

    I just saw another question very similar to this!

    Here is the canonical NORTHWIND (spelled just slightly different for some reason) database example.

    SELECT *
    FROM [NORTHWND].[dbo].[Products]
    

    SELECT CategoryId,
               MAX( CASE seq WHEN 1 THEN ProductName ELSE '' END ) + ', ' +
               MAX( CASE seq WHEN 2 THEN ProductName ELSE '' END ) + ', ' +
               MAX( CASE seq WHEN 3 THEN ProductName ELSE '' END ) + ', ' +
               MAX( CASE seq WHEN 4 THEN ProductName ELSE '' END )
          FROM ( SELECT p1.CategoryId, p1.ProductName,
                        ( SELECT COUNT(*) 
                            FROM NORTHWND.dbo.Products p2
                            WHERE p2.CategoryId = p1.CategoryId
                            AND p2.ProductName <= p1.ProductName )
                 FROM NORTHWND.dbo.Products p1 ) D ( CategoryId, ProductName, seq )
         GROUP BY CategoryId ;
    

提交回复
热议问题