Premium problem74. Stockout Duration

Hard Locked

inventory_events(product_id, event_at, inventory_qty)

Each row is a snapshot of stock after a change, and it stays in effect until the next snapshot for that product. For each product, return the total hours during September 2026 where inventory_qty was 0, rounded to two decimals.

Two edges matter. A snapshot from before September still describes the stock on 1 September, so a stockout that began in August counts from midnight on the 1st. And the last snapshot of a product has no successor, so it runs to the end of the month.

Return product_id and stockout_hours, ordered by product_id. Products that were never out of stock in the month do not appear.

Filtering the events to September first throws away the August snapshot that is doing the most work here.

Tables

inventory_events

product_id  event_at             inventory_qty
----------  -------------------  -------------
1           2026-08-30 12:00:00  0
1           2026-09-01 06:00:00  10
1           2026-09-10 00:00:00  0
1           2026-09-10 12:00:00  5
2           2026-09-29 00:00:00  3
2           2026-09-30 00:00:00  0
3           2026-09-05 00:00:00  7

Expected result

product_id  stockout_hours
----------  --------------
1           18.00
2           24.00

Premium problem

This one's part of Premium. Unlock the full MySQL track plus every other premium problem on the site.

Write one SELECT query