新编号查询示例(分类查询).sql

/*--查询新编号的示例

    要求:
    按id前4位分组,查询出最小一组的缺号,如果没有,则用最大组的id+1

--邹建 2004.12(引用请保留此信息)--*/

--测试数据
create table tb(id int)
insert tb select 10010001
union all select 10010002
union all select 10010003
union all select 10010004
union all select 10010005
--union all select 10020001
union all select 10020002
union all select 10020003
union all select 10020004
union all select 10030001
go

--查询处理1(最小编号为:xxxx0001的处理)
select 新id=left(id,4)+right(10001+right(a.id,4),4)
from(
    select id=isnull(min(a.id),(select max(id) from tb))
    from(
        select id from tb
        union all
        select distinct left(id,4)+'0000' from tb
    )a left join(
        select id=max(id) from tb group by left(id,4)
    )b on a.id=b.id
    where b.id is null and     not exists(
        select * from tb where id=left(a.id,4)+right(10001+right(a.id,4),4))
)a

--查询处理2(最小编号为表中每组的最小编号)
select 新id=left(id,4)+right(10001+right(a.id,4),4)
from(
    select id=isnull(min(a.id),(select max(id) from tb))
    from tb a left join(
        select id=max(id) from tb group by left(id,4)
    )b on a.id=b.id
    where b.id is null and     not exists(
        select * from tb where id=left(a.id,4)+right(10001+right(a.id,4),4))
)a
go

--删除测试
drop table tb

/*--测试结果

新id              
----------------
10020001

(所影响的行数为 1 行)


新id              
----------------
10030002

(所影响的行数为 1 行)
--*/
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值