日期:2014-05-18  浏览次数:20403 次

收集表中行加入到另一表的一个字段中
原有表A
id value
0 a
0 b
0 c
1 b
1 c

希望得到下表:
id value
0 a/b/c
1 b/c

------解决方案--------------------
自定义函数
------解决方案--------------------
SQL code


create  function wsp(@id int)
returns varchar(50)
as
begin
    declare @sql varchar(8000)
    select @sql=isnull(@sql+'/','')+value from lo where id=@id
    return @sql
end



调用函数:
select distinct id,dbo.wsp(id) [value] from A

------解决方案--------------------
SQL code

CREATE   TABLE   #Tab   (  
id int,value varchar(10)
)

insert   into   #Tab
select  0, 'a' union   all  
select   0, 'b' union   all  
select   0, 'c' union   all  
select   1, 'b' union   all  
select   1, 'c'

select * into # from #tab order by id

declare @col1 varchar(100),@col2 varchar(1000)
update # set @col2=case when @col1=id then @col2+'/'+value else value end,@col1=id,value=@col2
select id,max(value) as value from # group by id
drop table #

------解决方案--------------------
SQL code


你可以参考如下:


/*
有表tb, 如下:
id    txt
----- ------
1     aa
1     bb
2     aaa
2     bbb
2     ccc

需要得到结果:
id     values
------ -----------
1      aa,bb
2      aaa,bbb,ccc

即: group by id, 求 txt 的和(字符串相加)
*/

create table tb(id int,txt varchar(100))
go
insert into tb
select 1,'aaa' union all
select 1,'bbb' union all
select 2,'ccc' union all
select 3,'ddd' union all
select 3,'eee' union all
select 3,'fff'

go
--写一个聚合函数:
create function dbo.fn_Merge(@id int)
returns varchar(8000)
as
begin
   declare @r varchar(8000)
   set @r=''
   select @r=@r+';'+txt from tb where id=@id
   return stuff(@r,1,1,'')
end
go

-- 调用函数
select id, dbo.fn_Merge(id) as txt from tb group by id
  
go
drop table tb
drop function fn_Merge