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

sql的问题(合并表的字段)
我用sql2000和asp.net做一个程序。有个点方是重数据库中读取值,用label显示。
有这样一张表,
表A
A1             A2                 A3
a               i                   aa
a               l                   bb
a               l                   cc
b               u                   dd
b               u                   ee
c               h                   ff
d               h                   gg
  我要得到的是这样一张表
A1             A2                 A3
a               i                   aa      
a               l                   bb+cc
b               u                   dd+ee
c               h                   ff
d               h                   gg
意思就是说   如果A1和A2的值都相同   就把A3的值加起来。
我想问问在数据库里怎么样实现       在程序里怎么实现。  


------解决方案--------------------
drop table A
go
create table A(A1 varchar(20),A2 varchar(20),A3 varchar(1000))
insert into A
select 'a ', 'i ', 'aa '
union all select 'a ', 'l ', 'bb '
union all select 'a ', 'l ', 'cc '
union all select 'b ', 'u ', 'dd '
union all select 'b ', 'u ', 'ee '
union all select 'c ', 'h ', 'ff '
union all select 'd ', 'h ', 'gg '
go
create function f_gets(@A1 varchar(20),@A2 varchar(20))
returns nvarchar(4000)
as
begin
declare @s nvarchar(4000)
set @s= ' '
select @s=@s+ '+ '+A3 from A where A1=@A1 and A2=@A2
set @s=stuff(@s,1,1, ' ')
return @s
end

go
select distinct A1,A2,dbo.f_gets(A1,A2) as A3
from A
/*
A1 A2 A3
-------------------- -------------------- --------
a i aa
a l bb+cc
b u dd+ee
c h ff
d h gg

(所影响的行数为 5 行)
*/