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

This is a Pro chapter

Sign in, then upgrade to Pro or Power to unlock this and the full Databases Mastery library.

A report needs to show month-over-month revenue change for the last 12 months. How do you write this efficiently?

Next Step

Continue to You're designing a multi-tenant SaaS for 10,000 tenants. Which isolation model and how do you prevent cross-tenant data leakage?← Back to all SQL questions