This took me way longer to untangle than I expected.
Start by identifying customers with at least one non-canceled order using a subquery or CTE. Then compute the three metrics separately: most recent completed/shipped order timestamp, distinct product count in last 7 days, and net spend in last 7 days after refunds. Finally, left join these metrics to the customer list and coalesce nulls to zero.
Pro tip: Clarify the definition of 'last 7 days'—whether it's relative to the current date or the latest order date—and explicitly state your assumption. Also, ensure refunds are subtracted only if the return timestamp falls within the same 7-day window, which may require a separate aggregation.
Use a subquery or CTE to select distinct customer IDs from orders where status is not 'canceled'. This forms the base population.
For each eligible customer, find the maximum order timestamp among orders with status 'completed' or 'shipped' across all time.
Filter orders to those with status 'completed' or 'shipped' and order timestamp within the last 7 days (relative to current date or latest date). Count distinct product IDs per customer.
Sum order amounts for completed/shipped orders in the last 7 days, then subtract the sum of refund amounts for returns with return timestamp in the same 7-day window. Ensure refunds are linked to the correct customer.
Left join the aggregated metrics to the eligible customer list and use COALESCE to replace nulls with 0 for the count and net spend metrics.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.