合并同一个id的多个值
现有一个表结构:
id value
1 zhang
1 wang
1 li
想转成如下结构
id value
1 zhang,wang,li
用sql语句怎么实现?
[解决办法]
----------------------------
-- Author :DBA_Huangzj(發糞塗牆)
-- Date :2013-05-15 17:50:33
-- Version:
-- Microsoft SQL Server 2008 R2 (SP1) - 10.50.2500.0 (X64)
--Jun 17 2011 00:54:03
--Copyright (c) Microsoft Corporation
--Enterprise Edition (64-bit) on Windows NT 6.1 <X64> (Build 7601: Service Pack 1, v.721)
--
----------------------------
--> 测试数据:[huang]
if object_id('[huang]') is not null drop table [huang]
go
create table [huang]([id] int,[value] varchar(5))
insert [huang]
select 1,'zhang' union all
select 1,'wang' union all
select 1,'li'
--------------开始查询--------------------------
SELECT a.[id] ,
STUFF(( SELECT ',' + [value]
FROM [huang] b
WHERE b.[id] = a.[id]
FOR
XML PATH('')
), 1, 1, '') '[value]'
FROM [huang] a
GROUP BY a.[id]
----------------结果----------------------------
/*
id [value]
----------- ----------------------------------------------------------------------------------------------------------------
1 zhang,wang,li
*/