Site icon Edu Venue

SQL Sum QTY Between Two Dates

I have this sample table:

Product    |   Category    |    QTY      |   Load Date
-----------+---------------+-------------+--------------
   1            Alpha           10         Jan. 1, 2021
   2            Beta            20         Jan. 1, 2021
   3           Charlie          20         Jan. 1, 2021
   1            Alpha           30         Jan. 2, 2021
   3           Charlie          30         Jan. 3, 2021
   1            Alpha          -50         Jan. 4, 2021
   2            Beta           -20         Jan. 4, 2021
   4            Delta           40         Jan. 4, 2021

I want to add a column that will sum the quantity base on Previous Load Date, and group by Product and Category.

How can I come up with an output as shown below?

Product    |   Category    |    QTY      |   Load Date   |  Sum_QTY
-----------+---------------+-------------+---------------+----------
   1            Alpha           10         Jan. 1, 2021       10
   2            Beta            20         Jan. 1, 2021       20
   3           Charlie          20         Jan. 1, 2021       20
   1            Alpha           30         Jan. 2, 2021       40
   3           Charlie          30         Jan. 3, 2021       50
   1            Alpha          -50         Jan. 4, 2021      -10
   2            Beta           -20         Jan. 4, 2021        0
   4            Delta           40         Jan. 4, 2021       40

Your help means a lot.

Thank you

Exit mobile version