问题是这样的:
我有一张表 表结构(部门,单证代码,单证号)
本来是清单形式,可是需求部门希望能够将同一部门同一单证代码的统一起来
即(部门,单证代码,单证起始号,单证终止号,份数)
我给如何处理好呢?
注:单证号中间有可以有断层的情况,只有连续的号码才能统计在一起。
及如 1 2 3 5 6 8 9
只能是 单证起始号 单证终止号 份数
          1          3        3
          5          6        2
          8          9        2
谢谢。  

解决方案 »

  1.   

    select 部门,单证代码,min(单证号),max(单证号) 单证终止号,count(*) 份数 
    from tb
    group by 
      

  2.   

    --方法1:利用比当前值大的最接近最小间断值的值(SQL2000)
    select MIN(col1) as startnum,
    grp as endnum
    from(
    select col1,
    (select MIN(col1) from T1 a where a.col1>=k.col1 and 
        not exists(select * from T1 where a.col1+1=col1 )) as grp
    from T1 k ) z 
    group by grp
    --方法2:利用ROW_NUMBER (sql2005)
    select MIN(col1) as startnum,
    max(col1) as endnum
    from(
    select col1,
    col1-ROW_NUMBER()over(order by col1) as grp
    from T1 k ) z 
    group by grp
    /*
    startnum    endnum
    ----------- -----------
    1           3
    100         101
    103         106*/
      

  3.   

    3楼厉害,学习了。我整理了一下
    if exists(select [name] from tempdb.dbo.sysobjects where id = object_id('tempdb..#temp1'))
    drop table #temp1select 1 as fldSeq into #temp1 union
    select 2 union
    select 3 union
    select 5 union
    select 6 union
    select 8 union
    select 9 select 
      MIN(fldSeq) as startnum,
      grp as endnum,
      grp - MIN(fldSeq) + 1 as Qty
    from(
    select fldSeq,
    (select MIN(fldSeq) from #temp1 a where a.fldSeq>=k.fldSeq and 
        not exists(select * from #temp1 where a.fldSeq+1=fldSeq )) as grp
    from #temp1 k ) z 
    group by grp/*
    startnum    endnum      Qty         
    ----------- ----------- ----------- 
    1           3           3
    5           6           2
    8           9           2(所影响的行数为 3 行)
    */