假设数据库中表A中“卡号”字段,普通查询:select 卡号 from A 得出结果如下:
8986010860510012102
8986010860510012106
8986010860510012107
8986010860510012108
8986010860510027968
8986010860510027969
8986010860510027970
8986010860511027971
8986010860510027969
8986010860510027970
8986010860511027972
8986010860510027973
希望得出如下结果
起始卡号         结尾卡号        数量
8986010860510012102 8986010860510012102 1
8986010860510012106 8986010860510012108 3
8986010860510027968 8986010860510027973 8
请教各位高手,该如何写啊?

解决方案 »

  1.   

    with tab as (select '102' as card from dual union 
    select '106' as card from dual union 
    select '107' as card from dual union 
    select '108' as card from dual union 
    select '968' as card from dual union 
    select '969' as card from dual union 
    select '970' as card from dual union 
    select '971' as card from dual )
    select t2.c1, t1.c1, (t1.c1 - t2.c1 + 1) as 数量
      from (select c1, c2, rownum xh
              from (select distinct t.c1, t.c2
                      from (select distinct card c1, card + 1 as c2 from tab) t
                     start with 1 = 1
                    connect by prior t.c2 = t.c1
                     order by t.c1)
             where c1 in (select card from tab)
               and c2 not in (select card from tab)) t1,
           (select c1, c2, rownum xh
              from (select distinct t.c1, t.c2
                      from (select distinct card c1, card + 1 as c2 from tab) t
                     start with 1 = 1
                    connect by prior t.c2 = t.c1
                     order by t.c1)
             where c1 in (select card from tab)
               and c1 - 1 not in (select card from tab)) t2
     where t1.xh = t2.xh
    说实话,我也有点绕晕了,但总算出来了,楼主先试试效果
    可以的话,我再解释