现在的位置: 首页 > 综合 > 正文

计算连续号处理方式.

2013年11月15日 ⁄ 综合 ⁄ 共 1184字 ⁄ 字号 评论关闭

原贴:http://community.csdn.net/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 行)

抱歉!评论已关闭.