advancedWindow Functions — ROW_NUMBER, RANK, LEAD, LAG

You need a sales report showing each sale's amount, the running total, the monthly average, and each salesperson's rank within their region. Can you write this as one query?

SELECT sale_id, salesperson_id, region, amount, SUM(amount) OVER (ORDER BY sale_date ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS running_total, AVG(amount) OVER (PARTITION BY DATE_TRUNC('month', sale_date)) AS monthly_avg, RANK() OVER (PARTITION BY region ORDER BY amount DESC) AS rank_in_region FROM sales ORDER BY sale_date, region. Explanation: Running total uses cumulative frame (ROWS U

This is a Pro chapter

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

You need a sales report showing each sale's amount, the running total, the monthly average, and each salesperson's rank within their region. Can you write this as one query?

Next Step

Continue to What is a CTE and how does it differ from a subquery?← Back to all SQL questions