表如下
voucherno      status
00001            0
00002            1
00003            0
00004            0
00005            1
00006            1
00007            1
类似于银行存折的状态,0代表库存,1代表已用,其他的还有作废、注销等
想做一个数据统计的SQL,获取的结果如下
起始印刷号     终止印刷号     数量    状态
00001          00001       1       0
00002          00002       1       1
00003          00004       2       0
00005          00007       3       1

解决方案 »

  1.   

    select min(voucherno),max(voucherno),count(*),status 
    from 
    (select status,voucherno,to_number(voucherno)-row_number() over(partition by status order by voucherno) rn  from a)
    group by status,rn
    order by 1
      

  2.   

    select 起始印刷号,e.voucherno 终止印刷号,终止印刷号-起始印刷号+1 数量, e.status 状态 from (
      select min(起始印刷号) 起始印刷号,终止印刷号 from (
        select a.voucherno 起始印刷号,
           isnull((select min(voucherno) - 1 from 
               t_voucher b
            where b.voucherno >a.voucherno and a.status <> b.status),
           (select max(voucherno) from t_voucher)) 终止印刷号
      from t_voucher a) c
    group by 终止印刷号) d,t_voucher e
    where d.终止印刷号 = e.voucherno