Calculate a running stock balance

Return movement id, item id, warehouse id and running balance ordered by movement id. Calculate balances separately for each item and warehouse.

Try it yourself

Open a fresh temporary warehouse inventory dataset. Write your query and use Check answer. Checking uses a separate, clean sample so edits to your workspace cannot change the expected answer. Matches are based on this dataset, not a proof for every possible database.

Open exercise →

Sample schema

warehouses(id, name)
items(id, sku, name, reorder_level)
stock(warehouse_id, item_id, quantity)
movements(id, item_id, warehouse_id, delta, moved_at)

About this dataset · Learning paths · SQL reference

Show a hint

SUM(delta) OVER (PARTITION BY item_id,warehouse_id ORDER BY moved_at,id ROWS UNBOUNDED PRECEDING).

Show one solution
SELECT id,item_id,warehouse_id,SUM(delta) OVER (PARTITION BY item_id,warehouse_id ORDER BY moved_at,id ROWS UNBOUNDED PRECEDING) FROM movements ORDER BY id;

Other queries can produce the same answer. Column aliases are ignored; column order and row order are checked.

Keep practicing

Count daily active users → · All exercises