在sql server中格式化数据

时间:2014-02-27 11:24:19

标签: sql sql-server sql-server-2008 tsql sql-server-2008-r2

这是我的SQL Server表格数据

            id  Name
            1   Active
            2    On-Hold
            3   Closed
            4    Cancelled
            5   Active
            6   On-Hold
            7   Closed
            8   Cancelled
            9   Active
            10  On-Hold
            11  Closed
            12  Cancelled

如何查询表格,使结果如下:

        Name        Id 
        Active     1,5,9
        On-Hold    2,6,10
        Closed     3,7,11
        Cancelled  4,8,12  

3 个答案:

答案 0 :(得分:2)

drop table #t
create table #t(id int,name varchar(20))
insert into #t values(1,'Active'),
            (2,'On-Hold'),
            (3 ,'Closed'),
            (4,'Cancelled'),
            (5,'Active'),
            (6,'On-Hold'),
            (7,'Closed'),
            (8,'Cancelled'),
            (9,'Active'),
            (10,'On-Hold'),
            (11,'Closed'),
            (12,'Cancelled')

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

 group by t2.name,t2.id

SEE DEMO

答案 1 :(得分:1)

SELECT
   t1.name,
   MemberList = substring((SELECT ( ', ' + CAST(id as varchar) )
                           FROM table t2
                           WHERE t1.name = t2.name
                           ORDER BY 
                              name
                           FOR XML PATH( '' )
                          ), 3, 1000 )FROM table t1
GROUP BY name

答案 2 :(得分:0)

使用XML PATH

SELECT distinct t1.Name, 
  SUBSTRING((
    SELECT ',' + cast(t2.Id as varchar(30))
    FROM Status t2
    WHERE t2.Name = t1.Name
    FOR XML PATH('')), 2, 1000000) as [Id List]
FROM Status t1

确保在

中交换真实的表名