如何制作一个高效的逗号分隔符

时间:2014-02-13 04:46:10

标签: sql sql-server

这是我的表

create table #t(id varchar(10),value varchar(10))

insert into #t values('0001','a'),('0001','b'),('0002','c'),('0002','d')

我需要一种有效的制作csv的方法

id    value
0001  a,b
0002  c,d

2 个答案:

答案 0 :(得分:2)

试试这个!

using Stuff with xml path('')

   select id,
stuff(
(
 select ',' + value from #t t1 where t1.id=t2.id for xml path(''),type).value('.','varchar(max)'),1,1,'') from #t t2

 group by t2.id

答案 1 :(得分:0)

Hello下面给出的要求两列都在VARCHAR中。因此我们可以使用SUBSTRING FUNCTION和CROSS APPLY来获得预期输出

DECLARE @t TABLE (ID VARCHAR(10) ,VALUE VARCHAR(10) )
INSERT INTO @t (ID,VALUE)VALUES ('0001','a')
INSERT INTO @t (ID,VALUE)VALUES ('0001','b')
INSERT INTO @t (ID,VALUE)VALUES ('0002','c')
INSERT INTO @t (ID,VALUE)VALUES ('0002','d')
INSERT INTO @t (ID,VALUE)VALUES ('0003','e')
INSERT INTO @t (ID,VALUE)VALUES ('0003','f')
SELECT  [Id], 
        SUBSTRING(d.Value,1, LEN(d.Value) - 1) VALUE
FROM
        (
            SELECT DISTINCT [Id]
            FROM @t
        ) a
        CROSS APPLY
        (
            SELECT Value + ', ' 
            FROM @t AS B 
            WHERE A.[Id] = B.[Id]
            FOR XML PATH('')
        ) D (Value)