多行到一个逗号分隔值不同的ID

时间:2017-03-17 09:20:31

标签: sql sql-server concat sql-server-group-concat

  

这个问题在这里已有答案:
  Multiple rows to one comma-separated value [duplicate] 1回答

我想在SQL Server中创建一个表值函数,我希望以逗号分隔值返回数据。

例如表:tbl

ID | Value
---+-------
 1 | 100
 1 | 200
 1 | 300  
 2 | 600
 2 | 700

现在,当我在SQL Server中执行查询时,我希望表格如下:

ID | Value
---+-------
 1 | 100,200,300
 2 | 600,700

3 个答案:

答案 0 :(得分:3)

测试数据

DECLARE @Table1 TABLE(ID INT, Value INT)
INSERT INTO @Table1 VALUES (1,100),(1,200),(1,300),(1,400)

<强>查询

SELECT  ID
       ,STUFF((SELECT ', ' + CAST(Value AS VARCHAR(10)) [text()]
         FROM @Table1 
         WHERE ID = t.ID
         FOR XML PATH(''), TYPE)
        .value('.','NVARCHAR(MAX)'),1,2,' ') List_Output
FROM @Table1 t
GROUP BY ID

结果集

╔════╦═════════════════════╗
║ ID ║     List_Output     ║
╠════╬═════════════════════╣
║  1 ║  100, 200, 300, 400 ║
╚════╩═════════════════════╝

答案 1 :(得分:2)

使用STUFF方法获得结果:

CREATE TABLE #table ( ID INT, Value INT)
INSERT INTO #table ( ID , Value )
SELECT  1 , 100 UNION ALL
SELECT   1 , 200 UNION ALL
SELECT  1 , 300   UNION ALL
SELECT  2 , 600 UNION ALL
SELECT  2 , 700

  SELECT ID , STUFF
 (
    (
     SELECT  ', ' + CAST(Value AS VARCHAR)
     FROM #table Inr WHERE inr.ID = Otr.ID FOR XML PATH('')
     ),1,1,'') 
 FROM #table Otr
 GROUP BY ID

答案 2 :(得分:1)

    CREATE TABLE #Table1
        ([ID] int, [Value] int)
    ;

    INSERT INTO #Table1
        ([ID], [Value])
    VALUES
        (1, 100),
        (1, 200),
        (1, 300),
        (2, 600),
        (2, 700)



    select  id
       ,stuff((select ', ' + cast(value as varchar(10)) [text()]
         from #table1 
         where id = t.id
         for xml path(''), type)
        .value('.','nvarchar(max)'),1,2,' ') value
from #table1 t
group by id

输出

ID  Value
1    100, 200, 300
2    600, 700