计算连续号处理方式.

博客围绕一批商品ID连号合并问题展开,给出原始数据及期望结果。通过SQL代码,先创建表并插入数据,再进行查询处理,将连号的ID合并,中间用“-”连接,最终得到合并后的结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原贴:http://community.youkuaiyun.com/Expert/topic/4428/4428867.xml?temp=.4289362

id        批次
10001      1
10002      1
10003      1
。。。     1
10011      1
20001      2
20002      2
20003      3
想得到的结果
id        批次
10001-11   1
20001-2    2
20003      3
就是说只要是一批商品,他的id都是连号,如果此批不止一条就合并末尾数不一样的中间用一个“-”符号,每一批的数量在另一个表中有值

--更正显示结果.
declare @t table(id varchar(10),批次 int)
insert into @t select '10001',1
union all select '10002',1
union all select '10003',1
union all select '10004',1
union all select '10005',1
union all select '10006',1
union all select '10007',1
union all select '10008',1
union all select '10009',1
union all select '10010',1
union all select '10011',1
union all select '20001',2
union all select '20002',2
union all select '20003',3


--查询处理
select  id=case when b.id=b.id1 then b.id
                else b.id+'-'+cast(convert(int,b.id1)-convert(int,b.id)+1 as varchar(10)) end,
        批次=a.批次
from @t a,(
 select id,id1=(select min(id) from @t a1
  where id>=a.id
   and not exists(
    select * from @t
    where 批次=a1.批次 and id=a1.id+1))
 from @t a
 where not exists(
  select * from @t
  where 批次=a.批次 and id=a.id-1))b
where a.id between b.id and b.id1
group by
b.id,b.id1,a.批次

--结果
id                    批次         
--------------------- -----------
10001-11              1
20001-2               2
20003                 3

(所影响的行数为 3 行)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值