intermediateTop 30 Scenario-Based Questions
A report needs to show month-over-month revenue change for the last 12 months. How do you write this efficiently?
WITH monthly AS (SELECT DATE_TRUNC('month', order_date) AS month, SUM(amount) AS revenue FROM orders WHERE order_date >= NOW() - INTERVAL '13 months' GROUP BY 1) SELECT month, revenue, LAG(revenue, 1, 0) OVER (ORDER BY month) AS prev_month, revenue - LAG(revenue, 1, 0) OVER (ORDER BY month) AS abs_change, ROUND(100.0 * (revenue - LAG(revenue, 1, 1)) OVER (ORDER BY month) / NULLIF(LAG(revenue, 1, 1
Ready to master this question?
Generate a complete walkthrough — background, the full answer in plain language, a working code example explained line by line, a real-world scenario, common mistakes, and how this same question gets asked in different ways.
Sign in to generate a response