table如下字段 ID     单号     类型
a      001      1
b      002      1
c      003      2
d      004      2
e      005      1
f      006      1
查出来的结果:
单号数量   起始单号   终止单号      类型
   2         001        002           1
   2         003        004           2
   2         005        006           1查出来的顺序不能变

解决方案 »

  1.   

    if object_id('[tb]') is not null drop table [tb]
    go
    create table [tb]([ID] varchar(1),[单号] varchar(3),[类型] int)
    insert [tb]
    select 'a','001',1 union all
    select 'b','002',1 union all
    select 'c','003',2 union all
    select 'd','004',2 union all
    select 'e','005',1 union all
    select 'f','006',1
    go;with cte as(
    select rn=row_number() over(order by getdate()),* from tb
    )
    SELECT COUNT(1) AS 单号数量,MIN(单号) AS 起始单号,MAX(单号) as 终止单号,类型
    FROM(
    select gid=rn-(select count(1) from cte where 类型=t.类型 and rn<=t.rn),*
    from cte t
    ) t2
    GROUP BY 类型,GID
    ORDER BY MIN(单号) /**
    单号数量        起始单号 终止单号 类型
    ----------- ---- ---- -----------
    2           001  002  1
    2           003  004  2
    2           005  006  1(3 行受影响)
    **/
      

  2.   


    with cte as(
    select row_no=row_number() over(order by getdate()),* from tb
    )
    SELECT COUNT(1) AS 单号数量,MIN(单号) AS 起始单号,MAX(单号) as 终止单号,类型
    FROM(
    select gid=row_no-(select count(1) from cte where 类型=t.类型 and rn<=t.rn),*
    from cte t
    ) t2
    GROUP BY 类型,GID
    ORDER BY MIN(单号)
    树哥真速度