/* 有表tb, 如下: f1 f2 ----- ------ 中国 CAN; 中国 PEK; 中国 MJU; 欧洲 ABC; 欧洲 EAC; 欧洲 CEF; 欧洲 TGD;需要得到结果:如何得到 中国 CAN;PEK;MJU 欧洲 ABC;EAC;CEF;TGD; 即: group by id, 求 txt 的和(字符串相加) */create table tb(f1 varchar(100),f2 varchar(100)) go insert into tb select '中国','CAN' union all select '中国','PEK' union all select '中国','MJU' union all select '欧洲','ABC' union all select '欧洲','EAC' union all select '欧洲','CEF' union all select '欧洲','TGD'go --写一个聚合函数: create function dbo.fn_Merge(@f varchar(100)) returns varchar(8000) as begin declare @r varchar(8000) set @r='' select @r=@r+';'+f2 from tb where f1=@f return stuff(@r,1,1,'') end go-- 调用函数 select f1, dbo.fn_Merge(f1) as f1 from tb group by f1
go drop table tb drop function fn_Merge
--改 /* 有表tb, 如下: f1 f2 ----- ------ 中国 CAN; 中国 PEK; 中国 MJU; 欧洲 ABC; 欧洲 EAC; 欧洲 CEF; 欧洲 TGD;需要得到结果:如何得到 中国 CAN;PEK;MJU 欧洲 ABC;EAC;CEF;TGD; 即: group by id, 求 txt 的和(字符串相加) */create table tb(f1 varchar(100),f2 varchar(100)) go insert into tb select '中国','CAN;' union all select '中国','PEK;' union all select '中国','MJU;' union all select '欧洲','ABC;' union all select '欧洲','EAC;' union all select '欧洲','CEF;' union all select '欧洲','TGD;'go --写一个聚合函数: create function dbo.fn_Merge(@f varchar(100)) returns varchar(8000) as begin declare @r varchar(8000) set @r='' select @r=@r+f2 from tb where f1=@f return stuff(@r,1,1,'') end go-- 调用函数 select f1, dbo.fn_Merge(f1) as f1 from tb group by f1
有表tb, 如下:
f1 f2
----- ------
中国 CAN;
中国 PEK;
中国 MJU;
欧洲 ABC;
欧洲 EAC;
欧洲 CEF;
欧洲 TGD;需要得到结果:如何得到
中国 CAN;PEK;MJU
欧洲 ABC;EAC;CEF;TGD;
即: group by id, 求 txt 的和(字符串相加)
*/create table tb(f1 varchar(100),f2 varchar(100))
go
insert into tb
select '中国','CAN' union all
select '中国','PEK' union all
select '中国','MJU' union all
select '欧洲','ABC' union all
select '欧洲','EAC' union all
select '欧洲','CEF' union all
select '欧洲','TGD'go
--写一个聚合函数:
create function dbo.fn_Merge(@f varchar(100))
returns varchar(8000)
as
begin
declare @r varchar(8000)
set @r=''
select @r=@r+';'+f2 from tb where f1=@f
return stuff(@r,1,1,'')
end
go-- 调用函数
select f1, dbo.fn_Merge(f1) as f1 from tb group by f1
go
drop table tb
drop function fn_Merge
/*
有表tb, 如下:
f1 f2
----- ------
中国 CAN;
中国 PEK;
中国 MJU;
欧洲 ABC;
欧洲 EAC;
欧洲 CEF;
欧洲 TGD;需要得到结果:如何得到
中国 CAN;PEK;MJU
欧洲 ABC;EAC;CEF;TGD;
即: group by id, 求 txt 的和(字符串相加)
*/create table tb(f1 varchar(100),f2 varchar(100))
go
insert into tb
select '中国','CAN;' union all
select '中国','PEK;' union all
select '中国','MJU;' union all
select '欧洲','ABC;' union all
select '欧洲','EAC;' union all
select '欧洲','CEF;' union all
select '欧洲','TGD;'go
--写一个聚合函数:
create function dbo.fn_Merge(@f varchar(100))
returns varchar(8000)
as
begin
declare @r varchar(8000)
set @r=''
select @r=@r+f2 from tb where f1=@f
return stuff(@r,1,1,'')
end
go-- 调用函数
select f1, dbo.fn_Merge(f1) as f1 from tb group by f1
go
drop table tb
drop function fn_Merge