SQL Query for Grouping the results based on sequence

后端 未结 6 1762
南旧
南旧 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:30

    Since Andriy has already posted the gold solution, here's my take using an UPDATE statement to get the result from a temp table, just for fun.

    declare @tmp table (
        id int, seq int, amt money, start int, this int, total money,
        primary key clustered(id, seq))
    ;
    insert @tmp
    select *, start=seq, this=seq, total=convert(money,amt)
    from btable
    ;
    declare @id int, @seq int, @start int, @amt money
    update @tmp
    set 
        @amt = total = case when id = @id and seq = @seq+1 then @amt+total else amt end,
        @start = start = case when id = @id and seq = @seq+1 then @start else seq end,
        @seq = this = seq,
        @id = id = id
    from @tmp
    option (maxdop 1)
    ;
    select id, start, max(this) [end], max(total) total
    from @tmp
    group by id, start
    order by id, start
    

    Notes:

    • btable: your table name
    • id int, seq int, amt money: expected columns in your table

提交回复
热议问题