zoukankan      html  css  js  c++  java
  • 新编号查询示例(分类查询).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 行)
    --*/
  • 相关阅读:
    正则表达式基础知识
    成功的基本法则
    Java实现简单的格式化信函生成器
    C实现哈希表
    C实现求解给定文本中以指定字符开头和结尾的子串数量的三种算法
    Java实现求解二项式系数及代码重构
    Java 异常处理学习总结
    C实现大整数幂求模问题的两种算法
    linux 学习前言
    提高编程能力的10种方法
  • 原文地址:https://www.cnblogs.com/shihao/p/2508629.html
Copyright © 2011-2022 走看看