SQL Query for Grouping the results based on sequence

后端 未结 6 1777
南旧
南旧 2020-12-11 01:40

I have a table like this:

ID  Seq  Amt
1   1    500
1   2    500
1   3    500
1   5    500
2   10   600
2   11   600
3   1    700
3   3    700
6条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-11 02:24

    This seems to work nicely. @breakingRows will contain all rows that break the sequence of id and seq (i.e. if id changes or if seq is not 1 more than the previous seq). With that table you can select all rows of such a sequence within @temp. I must add however that performance will probably be not all that good because of all the subqueries but you'll need to test to be sure.

    declare @temp table (id int, seq int, amt int)
    insert into @temp select 1, 1, 500
    insert into @temp select 1, 2, 500
    insert into @temp select 1, 3, 500
    insert into @temp select 1, 5, 500
    insert into @temp select 2, 10, 600
    insert into @temp select 2, 11, 600
    insert into @temp select 3, 1, 700
    insert into @temp select 3, 3, 700
    
    declare @breakingRows table (ctr int identity(1,1), id int, seq int)
    
    insert into @breakingRows(id, seq)
    select id, seq
    from @temp t1 
    where not exists 
        (select 1 from @temp t2 where t1.id = t2.id and t1.seq - 1 = t2.seq)
    order by id, seq
    
    select br.id, br.seq as start, 
           isnull ((select top 1 seq from @temp t2 
                   where id < (select id from @breakingRows br2 where br.ctr = br2.ctr - 1) or 
                         (id = (select id from @breakingRows br2 where br.ctr = br2.ctr - 1) and
                          seq < (select seq from @breakingRows br2 where br.ctr = br2.ctr - 1))          
                   order by id desc, seq desc),
                   br.seq)
          as [end],
          (select SUM(amt) from @temp t1 where t1.id = br.id and 
            t1.seq < 
                isnull((select seq from @breakingRows br2 where br.ctr = br2.ctr - 1 and br.id = br2.id), 
                       (select max(seq) + 1 from @temp)) and 
            t1.seq >= br.seq)
    from @breakingRows br
    order by id, seq
    

提交回复
热议问题