sql列合并


表結構如下:

idvalue
-----------
1aa
1bb
2aaa
2bbb
2ccc

結果如下:
idvalues
-----------------
1aa,bb
2aaa,bbb,ccc
*/

create table tb(id int ,value varchar ( 10 ))
insert into tb values ( 1 , ' aa ' )
insert into tb values ( 1 , ' bb ' )
insert into tb values ( 2 , ' aaa ' )
insert into tb values ( 2 , ' bbb ' )
insert into tb values ( 2 , ' ccc ' )
go

-- ----------------------------------------------------------
--
1.sql2000舊方法:利用函數
create function dbo.f_str( @id int )
returns varchar ( 8000 )
as
begin
declare @r varchar ( 8000 )
set @r = ''
select @r = @r + ' , ' + value from tb where id = @id
return STUFF ( @r , 1 , 1 , '' )
end
go
select id,value = dbo.f_str(id) from tb group by id

-- ----------------------------------------------------------
--
2.sql2000舊方法:另一個函數
create function f_hb( @id int )
returns varchar ( 8000 )
as
begin
declare @str varchar ( 8000 )
set @str = ''
select @str = @str + ' , ' + cast (value as varchar ) from tb where id = @id
set @str = right ( @str , len ( @str ) - 1 )
return ( @str )
end
go
select distinct id,dbo.f_hb(id) as value from tb

-- ----------------------------------------------------------
--
3.sql2005:outerapply
select A.id,B. [ newValues ] from
(
select distinct id from tb)A
outer apply
(
select [ newValues ] = stuff ( replace ( replace (
(
select [ value ] from tbN
where id = A.id
for xmlauto
),
' <Nvalue=" ' , ' , ' ), ' "/> ' , '' ), 1 , 1 , '' )
)B

/*
注:APPLY是在一个查询的FROM子句中指定的新的关系运算符。
它允许您对外部表的每一行调用表值函数,可选地使用外部表的列作为函数的参数。
APPLY运算符有两种形式:CROSSAPPLY和OUTERAPPLY。
如果表值函数为其返回一个空集合的话,前者不返回外部表的行,而后者则返回一个NULL值的行而不是函数的列。
*/

-- ----------------------------------------------------------
--
4.sql2005:forxmlpath
select id, [ values ] = stuff (( select ' , ' + [ value ] from tbt where id = tb.id for xmlpath( '' )), 1 , 1 , '' )
from tb

groupbyid


引用自:http://www.haogongju.net/art/782866


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值