How does the RANK() window function work when partitioned by region_name to rank customers by total revenue, and how would you write such a query?
1Times asked
Jul 2026Last seen
Jul 2026First seen
💡 Model Answer
The RANK() function assigns a rank to each row within a partition based on the order of a specified expression. When you partition by region_name and order by total revenue descending, each region gets its own ranking sequence. Ties receive the same rank, and the next rank is skipped accordingly.
Example query:
sql
SELECT
region_name,
customer_id,
SUM(unit_price * quantity) AS total_revenue,
RANK() OVER (PARTITION BY region_name ORDER BY SUM(unit_price * quantity) DESC) AS revenue_rank
FROM sales
WHERE status = 'completed'
GROUP BY region_name, customer_id
ORDER BY region_name, revenue_rank;Explanation:
SUM(unit_price * quantity)aggregates revenue per customer.- The
WHEREclause filters only completed orders. PARTITION BY region_namerestarts the ranking for each region.ORDER BY ... DESCranks higher revenue first.RANK()outputs the rank; customers with identical revenue share the same rank.
This pattern is useful for generating leaderboards or identifying top performers within each geographic segment.
This answer was generated by AI for study purposes. Use it as a starting point — personalize it with your own experience.
🎤 Get questions like this answered in real-time
Assisting AI listens to your interview, captures questions live, and gives you instant AI-powered answers on a discreet on-screen overlay.
Get Assisting AI — Starts at ₹500