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
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