--测试数据 Create table t (id varchar(5),公司 varchar(6),职员 varchar(4),金额 money) insert into t select 'F0001','A公司','王三',100 union all select 'F0001','A公司','李杰',200 union all select 'F0001','B公司','张静',300 union all select 'F0002','A公司','李五',150 union all select 'F0002','C公司','赵为',350 --函数 Create function F_TGetStr(@Item as varchar(10),@bit bit) returns varchar(200) as begin declare @s as varchar(200) set @s='' if @bit=0 begin select @s=@s+','+ltrim(rtrim(公司)) from (select distinct 公司 from T where id=@item) A end if @bit=1 begin select @s=@s+'/'+ltrim(rtrim(职员)) from (select distinct 职员 from T where id=@item) A end return stuff(@s,1,1,'') end--查询 select id,公司=dbo.F_TGetStr(id,0),职员=dbo.F_TGetStr(ID,1),金额=sum(金额) from t group by ID --结果 id 公司 职员 金额 ----- -------------------- -------------------- --------------------- F0001 A公司,B公司 李杰/王三/张静 600.0000 F0002 A公司,C公司 李五/赵为 500.0000(所影响的行数为 2 行)--删除环境和函数 drop table T drop function F_TGetStr
--测试环境 declare @t table(name varchar(20)) insert @t select '张三' union all select '李四' union all select '王五' --查询 declare @s varchar(2000) set @s='' select @s=@s+'/'+name from @t select stuff(@s,1,1,'') --结果 张三/李四/王五(所影响的行数为 1 行)
--测试数据
Create table t (id varchar(5),公司 varchar(6),职员 varchar(4),金额 money)
insert into t select 'F0001','A公司','王三',100
union all select 'F0001','A公司','李杰',200
union all select 'F0001','B公司','张静',300
union all select 'F0002','A公司','李五',150
union all select 'F0002','C公司','赵为',350
--函数
Create function F_TGetStr(@Item as varchar(10),@bit bit)
returns varchar(200)
as
begin
declare @s as varchar(200)
set @s=''
if @bit=0
begin
select @s=@s+','+ltrim(rtrim(公司)) from
(select distinct 公司 from T where id=@item)
A
end
if @bit=1
begin
select @s=@s+'/'+ltrim(rtrim(职员)) from
(select distinct 职员 from T where id=@item)
A
end
return stuff(@s,1,1,'')
end--查询
select id,公司=dbo.F_TGetStr(id,0),职员=dbo.F_TGetStr(ID,1),金额=sum(金额)
from t group by ID
--结果
id 公司 职员 金额
----- -------------------- -------------------- ---------------------
F0001 A公司,B公司 李杰/王三/张静 600.0000
F0002 A公司,C公司 李五/赵为 500.0000(所影响的行数为 2 行)--删除环境和函数
drop table T
drop function F_TGetStr
declare @t table(name varchar(20))
insert @t select '张三'
union all select '李四'
union all select '王五' --查询
declare @s varchar(2000)
set @s=''
select @s=@s+'/'+name from @t
select stuff(@s,1,1,'')
--结果
张三/李四/王五(所影响的行数为 1 行)