【Transact-SQL】通过递归来实现:将多条记录的某个字段的值,用斜杠拼接在一起

来源:互联网 发布:数据挖掘原理 张银奎 编辑:程序博客网 时间:2024/06/05 06:59

 需要把表@tt中的idd相同的记录中tchar字段的内容拼接在一起,结果如下

1,'abc/xyz/ggg'

2,'111/soft'

 

实验代码如下:

declare @tt table(idd int,tchar varchar(10))insert into @tt    select 1,'abc' union allselect 1,'xyz' union allselect 1,'ggg' union allselect 2,'111' union allselect 2,'soft' ;with cas(select idd,       tchar,   row_number() over(partition by idd order by tchar) as rowfrom @tt ),cc   --递归CTEas(select idd,           cast(tchar as varchar(1000)) as ch,   rowfrom c where row = 1    union allselect cc.idd,           ch=cast(cc.ch+'/'+c.tchar as varchar(1000)),           c.rowfrom ccinner join c on c.idd = cc.idd   and c.row = cc.row+1),cccas(select idd,ch,row,       row_number() over(partition by idd order by row desc) as rownumfrom cc)select * from ccc where rownum=1/*iddch        rowrownum1abc/ggg/xyz312111/soft21*/


原创粉丝点击