多条记录合并为一条,同时将连续的编号写成“起始编号-结束编号”的形式

例如:

表 a: 
tmh       id
000055 2
000057 2
000059 2
000060 2
000061 2
000062 2
000063 2
000064 2
000065 3
000066 1
000600 1

要求得到如下结果: 
tmh                                               id
000055,000057,000059-000064  2
000065                                         3
000066,000600                            1
将值相同的记录合并成一行,同时将连续的编号写成“起始编号-结束编号”的形式。

 

 

 

解决:

 

--☆子灵☆

--2009-09-23

create function tmhconvert(@id int)
returns varchar(2000)
as
begin
 declare
 @alltmh varchar(2000),--存放最后结果
 @pretmh varchar(20),--前一个条码号
 @flag bit,--0表示已经找到连续的,1表示没有。
 @count int--用于判断是否运行到最后一条。
 set @flag=1;
 set @alltmh='';
 select @count=count(*) from a where id=@id;
 select @alltmh=@alltmh+case
  when @pretmh is null then
   tmh
  when cast(@pretmh as int)+1=cast(tmh as int) then
   case @count
    when 1 then '-'+tmh
    else ''
   end
  else
   case @flag
    when 0 then '-'+@pretmh+','+tmh
    when 1 then ','+tmh
   end
  end,
  @flag=case
  when cast(@pretmh as int)+1=cast(tmh as int) then
   0
  else
   1
  end,
  @pretmh=tmh,
  @count=@count-1
 from a where id=@id;
 return @alltmh;
end

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值