Search code examples
sqlrequestcumulative-sum

Cumulative / Running total group by one column


I want to calculate cumulative column. The result i want it's in 2nd table in column "Cumul_result".

I have this table :

enter image description here

I want to calculate Running total group by article. For exemplace te result will be : | Article  |      YEAR   |Quantity       |Cumulative_result
| -------- |--------     |-------------- |------------------|
| 1        |    2022     |0              |0                 |
| 1        |    2023     |10             |10                |
| 1        |    2024     |100            |110               |
| 526      |    2020     |50             |50                |
| 526      |    2021     |0              |0                 |
| 526      |    2022     |10             |60                |
| 852      |   2021      |1              |1                 |
| 852      |   2020      |0              |1                 |

I try this request bu it's not work :

select Article,
       Year,
       Quantity ,
       Sum(Quantity) over ( order by  Year) as Cumul_result
  
FROM TABLE;

Can you help me please ? Thanks


Solution

  • You are almost correct, all you need to do is partition by Article:

    select Article,
           Year,
           Quantity ,
           Sum(Quantity) over (partition by Article order by Year) as Cumul_result
    FROM mytable;