TSQL-将一个表中多行的数据合并到一行数据

题目描述:按照id:vertex格式把所有行记录按照id从小到大合并到一行记录中。

数据如下表:

表数据

 预期结果如下图:

预期结果


解决方案:

方案一:基于游标

declare t_cur cursor  
	for select id,vertex from temp order by id;
declare @result varchar(max);
declare @id int;
declare @vertex varchar(10);
set @result = '';

open t_cur;
fetch t_cur into @id,@vertex;
while(@@fetch_status = 0)
begin
	set @result = @result + cast(@id as varchar) + ':' + isnull(@vertex,'') + ',';
	fetch t_cur into @id,@vertex;
end
close t_cur;
deallocate t_cur;
方案二:一条SQL语句
declare @result varchar(max)
set @result = ''
select @result = @result + cast(id as varchar) + ':'+ isnull(vertex,'') + ','
from temp 
order by id

--delete the last comma
set @result = substring(@result,1,len(@result)-1)
select @result


结论:

       显然第二个解决方案的效率比第一个要高,但是就解决问题而言,如果能想到好的解决方案固然很好,如果想不到好的解决方案,游标至少是一种可行的解决方案。
       If you can't find a good solution, then you should hug your "bad" one.


参考:

[1]  T-SQL – How to select multiple rows into a single row

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值