下文将为您介绍SQL语句中如何进行同列相加的写法,相加是SQL中经常用到的操作,该方法供您参考,希望对您有所帮助 。
Create table Tab([Col1] int,[Col2] nvarchar(1))
Insert Tab
select 1,Na union all
select 1,Nb union all
select 1,Nc union all
select 2,Nd union all
select 2,Ne union all
select 3,Nf
Go
create function F_Str(@Col1 int)
returns nvarchar(100)
as
begin
declare
@S nvarchar(100)
select @S=isnull(@S,)+Col2 from Tab where Col1=@Col1
return @S
end
go
Select distinct Col1,Col2=dbo.F_Str(Col1) from Tab
go
================================
说明:
目标:表的一列为字符串,要求把该列字符串连起来 。
如:
1,aa,
1,bb
2,cc
2,dd
结果:
1,aabb
2,ccdd
如果要出现aa,bb cc,dd的结果
那isnull(@S,)改成isnull(@S+,,)
isnull(@S,): 如果@S是空,则用代替,因为null+字符串 = null