计算连续号处理方式10001-11

本文介绍了一种使用SQL对连续批次的商品ID进行合并处理的方法,通过特定的查询语句实现对ID的有效组合,并展示了如何利用SQL脚本来实现这一功能。

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

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.批次

 

本文来自优快云博客:http://blog.youkuaiyun.com/zlp321002/archive/2005/11/30/540476.aspx

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值