KatInterview

Calculate Current Item Inventory from Movements and Baselines

SQL & DataModel answer
MediumModel answerSQL & Datasqlaggregationjoins

Last updated

Compute up-to-date item stock by merging starting snapshot balances with subsequent movement logs using SQL aggregations and joins.

You are managing an inventory system that tracks product stock movements over time. You have a starting inventory snapshot from the beginning of the period and a streaming ledger of all adjustments (such as shipments, returns, and sales) recorded since that snapshot.

Write an ANSI SQL query to compute the current overall stock for every item present in the baseline inventory dataset.

Schema Details

  1. inventory_baseline (Initial balance per product):

    • product_id (INT): Unique identifier for the item.
    • stock_count (INT): The quantity recorded at the starting point.
  2. inventory_transactions (Subsequent movement log):

    • transaction_id (INT): Primary key of the movement record.
    • product_id (INT): Identifier of the item moved.
    • change_amount (INT): Adjustment quantity (positive values denote added stock; negative values denote dispatched stock).
    • transaction_date (DATETIME): Timestamp of the event.

Target Output

Your query should yield a record set containing:

  • product_id
  • current_stock: The initial baseline stock plus the sum total of all valid changes recorded for that item.

Rules & Edge Cases

  • Include every product_id listed in inventory_baseline.
  • If an item in inventory_baseline has no entries in inventory_transactions, its output current_stock must equal its baseline quantity.
  • Transactions might reference a product_id not present in inventory_baseline; these non-baseline items should be omitted unless specified otherwise.
  • Aggregate operations must correctly treat missing movement totals as zero rather than NULL.