Bird
0
0

How can you calculate the percentage contribution of each sale amount to the total sales per region using window functions?

hard📝 Application Q9 of 15
PostgreSQL - Window Functions in PostgreSQL
How can you calculate the percentage contribution of each sale amount to the total sales per region using window functions?
ASELECT region, amount, amount * 100.0 / SUM(amount) OVER (PARTITION BY region) AS pct FROM sales
BSELECT region, amount, amount / SUM(amount) FROM sales GROUP BY region
CSELECT region, amount, RANK() OVER (PARTITION BY region ORDER BY amount) AS pct FROM sales
DSELECT region, amount, amount * 100 / COUNT(*) OVER (PARTITION BY region) AS pct FROM sales
Step-by-Step Solution
Solution:
  1. Step 1: Calculate total sales per region using window SUM()

    SUM(amount) OVER (PARTITION BY region) computes total sales for each region without grouping rows.
  2. Step 2: Compute percentage contribution

    Divide each amount by total sales per region and multiply by 100 for percentage.
  3. Final Answer:

    SELECT region, amount, amount * 100.0 / SUM(amount) OVER (PARTITION BY region) AS pct FROM sales -> Option A
  4. Quick Check:

    Use window SUM() for totals, then calculate percentage [OK]
Quick Trick: Use SUM() OVER PARTITION for totals, then compute percentage [OK]
Common Mistakes:
  • Using GROUP BY which aggregates rows losing detail
  • Using COUNT() instead of SUM() for totals
  • Confusing RANK() with percentage calculation

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PostgreSQL Quizzes