请帮忙解决一个问题谢谢!!!
表1
编号 wt1 wt2
001 aaa cccc
001 bbb ffff
001 ccc eeee
..................
..................
002 ssss yyyyy
请问如何将表1合并为表2,注:每个编号记录条数不固定。
表2
编号 wt wt2
001 aaa,bbb,ccc,..... cccc,ffff,eeee,......
002 ssss yyyy
------解决方案--------------------drop table 表1
create table 表1(编号 varchar(10),wt1 varchar(10),wt2 varchar(10))
insert into 表1
select '001 ', 'aaa ', 'cccc '
union all select '001 ', 'bbb ', 'ffff '
union all select '001 ', 'ccc ', 'eeee '
union all select '002 ', 'ssss ', 'yyyyy '
create function f_getstr1(@no varchar(10))
returns varchar(8000)
as
begin
declare @returnstr varchar(8000)
select @returnstr = ' '
select @returnstr = @returnstr + wt1+ ', ' from 表1 where 编号=@no
return left(@returnstr,len(@returnstr)-1)
end
create function f_getstr2(@no varchar(10))
returns varchar(8000)
as
begin
declare @returnstr varchar(8000)
select @returnstr = ' '
select @returnstr = @returnstr + wt2+ ', ' from 表1 where 编号=@no
return left(@returnstr,len(@returnstr)-1)
end
select 编号,dbo.f_getstr1(编号) as 'wt ',dbo.f_getstr2(编号) as 'wt1 ' from 表1
group by 编号
------解决方案--------------------樓上的兩個函數可以合併為一個
create table 表1(编号 varchar(10),wt1 varchar(10),wt2 varchar(10))
insert into 表1
select '001 ', 'aaa ', 'cccc '
union all select '001 ', 'bbb ', 'ffff '
union all select '001 ', 'ccc ', 'eeee '
union all select '002 ', 'ssss ', 'yyyyy '
GO
create function f_getstr(@no varchar(10), @Flag Int)
returns varchar(8000)
as
begin
declare @returnstr varchar(8000)
select @returnstr = ' '
select @returnstr = @returnstr + (Case @Flag When 1 Then wt1 Else wt2 End) + ', ' from 表1 where 编号=@no
return left(@returnstr,len(@returnstr)-1)
end
GO
select 编号,dbo.f_getstr(编号, 1) as 'wt ',dbo.f_getstr(编号, 2) as 'wt1 ' from 表1
group by 编号
GO
drop table 表1
Drop function f_getstr
------解决方案----------------------创建测试环境
create table 表1(编号 varchar(10),wt1 varchar(20),wt2 varchar(20))
--插入测试数据
insert 表1(编号,wt1,wt2)
select '001 ', 'aaa ', 'cccc ' union all
select '001 ', 'bbb ', 'ffff ' union all
select '001 ', 'ccc ', 'eeee ' union all
select '002 ', 'ssss ', 'yyyyy '
--求解过程
select * into #tmp from 表1 order by wt1,wt2
declare @id varchar(10),@wt1 varchar(8000) ,@wt2 varchar(8000)