求大神指教如何将多条记录合成为一条.例如:
1 a
1 b
1 c
1 d
1 e
合成为:
1 abcde
求大神指点!
sql
------解决方案--------------------
create table ta(id int,name varchar(10))
insert into ta
select 1,'a'
union all select 1,'b'
union all select 1,'c'
union all select 1,'d'
union all select 1,'e'
select a.id,
(select ''+name from ta b
where b.id=a.id
for xml path('')) 'name'
from ta a
group by a.id
/*
id name
---------------------
1 abcde
*/
------解决方案--------------------
----------------------------------------------------------------
-- Author :DBA_Huangzj(發糞塗牆)
-- Date :2013-10-12 09:56:50
-- Version:
-- Microsoft SQL Server 2014 (CTP1) - 11.0.9120.5 (X64)
-- Jun 10 2013 20:09:10
-- Copyright (c) Microsoft Corporation
-- Enterprise Evaluation Edition (64-bit) on Windows NT 6.2 <X64> (Build 9200: ) (Hypervisor)
--
----------------------------------------------------------------
--> 测试数据:[huang]
if object_id('[huang]') is not null drop table [huang]
go
create table [huang]([id] int,[name] varchar(1))
insert [huang]
select 1,'a' union all
select 1,'b' union all
select 1,'c' union all
select 1,'d' union all
select 1,'e'
--------------开始查询--------------------------
select a.id,REPLACE(
stuff((select ','+name from [huang] b
where b.ID=a.ID
for xml path('')),1,1,''),',','') 'name'
from [huang] a
group by a.ID
----------------结果----------------------------
/*
id name
----------- ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
1 abcde
*/
------解决方案--------------------
create table test(id int,name varchar)
insert into test
select '1','a'
union all select '2','b'
union all select '3','c'
union all select '4','d'
union all select '5','e'
select * from test;
select id=1,name=stuff((select ','+name from test for xml path('')),1,1,'')
------解决方案--------------------
declare @sql varchar(100)
set @sql=''
select @sql=@sql+col from #a
select distinct id,@sql from #a
------解决方案--------------------
if object_id('test') is not null
drop table test
go
create table test(id int,name varchar)
insert into test
select 1,'a'
union all select 1,'b'
union all select 1,'c'
union all select 1,'d'
union all select 1,'e'
--1.通过xml path来实现
select distinct id,
(select '' + t2.name
from test t2
where t1.id = t2.id
for XML path('')
) as name
from test t1
/*
id name
1 abcde
*/
--2.通过T-SQL来实现,在数据较多时性能较好,可能改写为函数
declare @str varchar(1000);
declare @id int;
set @str = '';
select @id = id,
@str = @str + name
from test
select @id as id,@str as name
/*
id name
1 abcde
*/
--3.把第二种改写为函数
--drop function dbo.fn_mergeSTR
create function dbo.fn_mergeSTR(@id int,@split varchar(10))
returns varchar(300)