表EXIME 字段 ID ,NAME 都是varchar型
当ID一样时候,把NAME放到同一个字段,用逗号隔开。
1 HUANG
1 LI
1 ZHANG
2 LIU
2 MA
3 WU
==
结果
1 HUANG,LI,ZHANG
2 LIU,MA
3 WU
------解决方案--------------------
http://bbs.csdn.net/topics/390299692
参考贴
------解决方案--------------------
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
------解决方案--------------------
使用CTE 有点麻烦。不过可行 DB2 和SQL server 2005以上都可以。
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