Interview Questions/SQL/FIFO Stock Cost Basis for Sales

FIFO Stock Cost Basis for Sales

Preview mode. Log in to edit, run, submit, and save progress.

Medium

Description

You are given Purchases and Sales tables for a single stock. Purchases arrive in date order; sales must consume inventory using FIFO (oldest lots first). For each sale, compute: total quantity sold, total cost basis (sum of units × their purchase price), and average cost per unit. Return (sale_id, sale_date, total_qty_sold, total_cost_basis, avg_cost_per_unit) ordered by sale_id. Table: Purchases

Column NameTypeDescription
purchase_idINTPrimary key
purchase_dateDATEDate of purchase
quantityINTUnits purchased
unit_costREALCost per unit

Table: Sales

Column NameTypeDescription
sale_idINTPrimary key
sale_dateDATEDate of sale
quantityINTUnits sold

Database Schema (Inferred)

Purchases

Column NameExample Value
purchase_id1
purchase_date2024-01-05
quantity100
unit_cost10

Sales

Column NameExample Value
sale_id1
sale_date2024-02-20
quantity120

Example

Purchases

purchase_idpurchase_datequantityunit_cost
12024-01-0510010
22024-02-1015012
32024-03-1520015

Sales

sale_idsale_datequantity
12024-02-20120
22024-04-01180

Output

sale_idsale_datetotal_qty_soldtotal_cost_basisavg_cost_per_unit
12024-02-20120124010.3333
22024-04-01180231012.8333

Explanation:

Sale 1 (qty=120): exhausts lot 1 (100 × $10 = $1000) then takes 20 from lot 2 (20 × $12 = $240). Total = $1240. Sale 2 (qty=180): takes remaining 130 from lot 2 (130 × $12 = $1560) then 50 from lot 3 (50 × $15 = $750). Total = $2310. Use cumulative sums to define lot ranges and overlap-match them to sale ranges.

Approach hint

Start with a simple approach, explain the trade-off, then move toward a cleaner or more scalable solution.

Common mistake

Skipping assumptions, edge cases, or trade-offs can make an otherwise good answer feel incomplete.

SQL Editor
Loading...

Purchases

purchase_idpurchase_datequantityunit_cost
12024-01-0510010
22024-02-1015012
32024-03-1520015

Sales

sale_idsale_datequantity
12024-02-20120
22024-04-01180

Output

sale_idsale_datetotal_qty_soldtotal_cost_basisavg_cost_per_unit
12024-02-20120124010.3333
22024-04-01180231012.8333