This thing had like five requirements stapled together and I kept losing track of which CTE was supposed to feed which.
Break the problem into modular CTEs: first aggregate weekly revenue per user, then compute rolling sums, week-over-week changes, and ranks using window functions. Separately calculate first and second purchase dates per user, then join and apply filters for revenue drop and top ranks.
Pro tip: Always clarify the definition of 'calendar week' (e.g., week starting Monday vs. Sunday) and how to handle users with no prior week (e.g., NULL for week-over-week change) to avoid off-by-one errors.
Create a CTE that groups transactions by user and calendar week, summing revenue. Ensure you handle weeks with zero revenue if needed, but typically only weeks with purchases are included.
Using the weekly revenue CTE, calculate a 4-week rolling sum, week-over-week percent change (using LAG), and a dense rank of users by rolling revenue within each week.
Create a separate CTE that finds each user's first and second purchase dates using ROW_NUMBER or MIN and filtering. Compute days between them, leaving NULL if no second purchase.
Join the weekly metrics with the purchase date info, then filter to rows where weekly revenue dropped at least 20% versus the prior week and where the dense rank is <= 3.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.