Search code examples
sqlsumgrouping

How to sum values of a column based on the increment values of another column in SQL


I have a table like below, now I want to sum up the values in column count as the values in day increases. I tried to query like below but it isn't working. As I am new to SQL just confused to create query which works for the above query.

Table:-

id     count  days
78112   4      2
78112   1      3
78112   2      5
8560    4      2
8560    4      4
9503    5      1
9503    3      2
9503    2      4
9503    5      6

Query:-

select id,sum(count),days from test group by id,days

This returns:-

id     count  days
78112   4      2
78112   1      3
78112   2      5
8560    4      2
8560    4      4
9503    5      1
9503    3      2
9503    2      4
9503    5      6

Excepted Output:-

id     count  days
78112   4      2
78112   5      3
78112   7      5
8560    4      2
8560    8      4
9503    5      1
9503    8      2
9503    10      4
9503    15      6

Solution

  • You need a running total partitioned by id.

    Select   id
            ,sum(count) over(partition by id order by days) as count
            ,days
    
    From     t
    order by cast(id as varchar(99)), days
    
    id count days
    78112 4 2
    78112 5 3
    78112 7 5
    8560 4 2
    8560 8 4
    9503 5 1
    9503 8 2
    9503 10 4
    9503 15 6

    Fiddle