zoukankan      html  css  js  c++  java
  • Oracle中实现sql查询得到连续号码段

    一、表名为t的表中数据如下:

    select * from t;
          FPHM       KSHM
    ---------- ----------
          2014          1
          2014          2
          2014          3
          2014          4
          2014          5
          2014          7
          2014          8
          2014          9
          2013        120
          2013        121
          2013        122
          2013        124
          2013        125

    实现代码如下:

    select b.fphm,min(b.kshm),max(b.kshm)
        from (
                select a.*,to_number(a.kshm-rownum) cc
                from (
                        select * from t order by fphm,kshm
                ) a
        )  b
        group by b.fphm,b.cc

    结果如下:

    FPHM            MIN(B.KSHM)   MAX(B.KSHM)
    ---------- ----------- ------------------
          2013         120         122
          2013         124         125
          2014           1           5
          2014           7           9
    

    ------------------------------------------------------------------------------------------------------------------------

    二、表名为gap的表中数据如下:

    select * from gap;
    
    ID SEQ
    ---------- ----------
    1 1
    1 4
    1 5
    1 8
    2 1
    2 2
    2 9

    实现代码如下:

    select res1.id, res2.seq str, res1.seq end
    from (
        select rownum rn, c.*
        from (
            select *
            from gap a
            where not exists (
                select null from gap b where b.id = a.id and a.seq = b.seq - 1
            )
            order by id, seq
        ) c
    ) res1, (
        select rownum rn, d.*
        from (
            select *
            from gap a
            where not exists (
                select null from gap b where b.id = a.id and a.seq = b.seq + 1
            )
            order by id, seq
        ) d
    ) res2
    where res1.id = res2.id
    and res1.rn = res2.rn

    结果如下:

    ID STR END
    --------- ---------- ----------
    1 1 1
    1 4 5
    1 8 8
    2 1 2
    2 9 9
  • 相关阅读:
    sublimetext ruby 插件
    [C]goto statement, rarely been used. Deprecated???
    [C]union
    [C] Struct Test
    [C,Java,Python]Command Line Argument: argv, argc, sys.argv, args
    [Python]**otherInfo, *other
    [C]parameterized macros 带参数的宏
    [C]指针与结构变量
    [C]结构变量传递给函数
    [C]结构变量数组array of structure varibles
  • 原文地址:https://www.cnblogs.com/hzjdpawn/p/12134359.html
Copyright © 2011-2022 走看看