如何将行非规范化为csv

时间:2015-11-15 00:50:18

标签: sql tsql

我有下表:

accelerometerUpdateInterval

有一种简单的方法来获得结果集:

id, name
---------------
1, Customer 01
1, Customer 02
2, Customer 01
3, Customer 01
3, Customer 03

我真的不需要括号。

1 个答案:

答案 0 :(得分:1)

使用for xml path

------------------------------------------------------------
--Create temp table for testing
IF OBJECT_ID('Tempdb..#Temp') IS NOT NULL 
    DROP TABLE #Temp

Create table #Temp
            (id Int, 
             name varchar(30))
Insert into #Temp
Values (1, 'Customer 01'),
       (1, 'Customer 02'),
       (2, 'Customer 01'),
       (3, 'Customer 01'),
       (3, 'Customer 03')

查询

SELECT DISTINCT
        o.id ,
        STUFF((SELECT  ',' + name
               FROM    #Temp AS i
               WHERE   i.ID = o.id
               FOR XML PATH('')),1,1,'') AS ConcatenatedName
FROM    #Temp AS o

测试在这里SQL FIDDLE