I have a table consisting of inventory data. The first row of the table is correct however for all the other rows, initial inventory should be the final inventory of the previous day and the final inventory should be initial inventory + recieved_sold of that date after having the correct initial inventory for that day . How can I do that in SQL?
Source
initial inventory date received_sold final inventory
20 1/1/23 -1 19
20 1/2/23 0 20
20 1/3/23 4 24
20 1/4/23 2 22
20 1/5/23 -2 18
expected:
initial inventory date received_sold final inventory
20 1/1/23 -1 19
19 1/2/23 0 19
19 1/3/23 4 23
23 1/4/23 2 25
25 1/5/23 -2 23
2条答案
按热度按时间pkwftd7m1#
For testing purposes, I used the following setup script:
Output of
SELECT * FROM inventory
:Updating columns
initial
andfinal
can be done in various ways. A simple solution is anUPDATE
statement with a subquery. For each row being updated, the subquery calculates the sum of all preceding rows.Expect this to run in O(n²) time. That might be OK for a small table, but for a large number of rows, it may be better to use a cursor. The following loop will update the rows one by one. Performance-wise, that is still far from ideal, but its time complexity can be close to O(n). Just try and see what works best for you.
Output of
SELECT * FROM inventory
:jogvjijk2#
You can do it using
row_number()
to get the first row, andfirst_value()
to get the initial final_inventory. the withsum over()
we get the expected data :Without
WITH
:The Update query can be as follows :
Demo here