The lateness calculation itself was fine, GREATEST(0, ...) to floor at zero is pretty standard.
Break the complex query into logical CTEs: first filter orders from the last 30 days and compute lateness in minutes using GREATEST and EXTRACT EPOCH, then add window functions for PERCENT_RANK and rolling 7-day refund cost, then simulate the tiered refund policy with a $50 cap and compare to current policy, and finally aggregate savings by city and identify top 5% store-days. Use clear aliases and comment each CTE to show structure and avoid errors.
Pro tip: Mention that the rolling 7-day refund cost should be computed at the store-day level using a window frame like ROWS BETWEEN 6 PRECEDING AND CURRENT ROW, and clarify that PERCENT_RANK is used to rank orders within each city and delivery date, which helps identify the top 5% store-days by current refund cost per order.
Filter orders from the last 30 days and compute lateness in minutes using GREATEST(0, EXTRACT(EPOCH FROM (delivered_at - promised_at))/60).
Use PERCENT_RANK() OVER (PARTITION BY city, delivery_date ORDER BY lateness_minutes) to rank orders, and compute rolling 7-day cold-food refund cost per order at store-day level using a window frame.
Calculate current refund (100% of subtotal) and proposed tiered refund (0% under 10 min, 50% for 10-29 min, 100% for 30+ min) with a $50 cap, then compute savings as the difference.
Aggregate savings by city and identify top 5% store-days by current refund cost per order using the PERCENT_RANK or a threshold.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.