日期:2014-05-17 浏览次数:20469 次
select a.ID ,
stuff((select ','+NAME from EXIME b
where b.ID =a.ID
for xml path('')),1,1,'') 'NAME '
from EXIME a
group by a.ID
CREATE TABLE [dbo].[temp](
[a] [varchar](20) NULL,
[b] [varchar](20) NULL
) ON [PRIMARY]
GO
INSERT [dbo].[temp] ([a], [b]) VALUES (N'1', N' HUANG')
INSERT [dbo].[temp] ([a], [b]) VALUES (N'1', N' LI')
INSERT [dbo].[temp] ([a], [b]) VALUES (N'1', N' ZHANG')
INSERT [dbo].[temp] ([a], [b]) VALUES (N'2', N' LIU')
INSERT [dbo].[temp] ([a], [b]) VALUES (N'2', N' MA')
INSERT [dbo].[temp] ([a], [b]) VALUES (N'3', N' WU')
INSERT [dbo].[temp] ([a], [b]) VALUES (N'3', N'MA')
INSERT [dbo].[temp] ([a], [b]) VALUES (N'4', N'ERE')
INSERT [dbo].[temp] ([a], [b]) VALUES (N'4', N'DFSAF')
INSERT [dbo].[temp] ([a], [b]) VALUES (N'4', N'ADFSD')
INSERT [dbo].[temp] ([a], [b]) VALUES (N'4', N'ADFD')
;with cte(rownum,a,b) as (
select rownum,a,cast(b as varchar(100))from (select ROW_NUMBER() over (partition by a order by a) as rownum,a,b from dbo.temp) a where a.rownum=1
union all
select b.rownum,b.a,cast(c.b+b.b as varchar(100)) from (select ROW_NUMBER() over (partition by a order by a) as rownum,a,b from dbo.temp ) b
inner join cte c
on c.a=b.a
and b.rownum=cast(c.rownum as integer)+1
)
select * from cte a INNER JOIN
(SELECT a,max(rownum) as rown from cte group by a) b
ON A.a=b.a
and a.rownum=b.rown
order by a.a