18. Ranking with Dense_Rank
Beginner Mode
Objective
Given a table named sales that records individual sales made by sales representatives, write a SQL query to compute the total sales for each salesperson. Assign a rank to each salesperson based on their total sales in descending order using dense ranking, ensuring that salespeople with identical total sales receive the same rank without gaps in the ranking sequence. The final output should list the salesperson's name, their total sales, and their sales rank, ordered first by rank and then alphabetically by name.
Additional information
Table Schema:
The
salestable:Column Type Description salesperson_id INTEGER Unique identifier for each salesperson salesperson_name VARCHAR Name of the salesperson sale_amount INTEGER Amount of an individual sale Constraints:
- The
salestable contains at least one record. - Total sales for each salesperson are calculated as the sum of their
sale_amountvalues. - Utilize SQL window functions to determine the sales rankings.
- The
Output Requirements:
- Columns to return:
| Column | Description |
|---|---|
| salesperson_name | Name of the salesperson |
| total_sales | Sum of all sales amounts for the salesperson |
| sales_rank | Dense rank based on total_sales in descending order |
- Order the results first by `sales_rank` in ascending order, then by `salesperson_name` in ascending order.
Examples
Example 1:
Output:
Input:
| sales | ||
|---|---|---|
| sale_amount | salesperson_id | salesperson_name |
| 5000 | 1 | Alice |
| 3000 | 1 | Alice |
| 4500 | 2 | Bob |
| 3500 | 2 | Bob |
| 8000 | 3 | Charlie |
| 8000 | 4 | Diana |
| sales_rank | salesperson_name | total_sales |
|---|---|---|
| 1 | Alice | 8000 |
| 1 | Bob | 8000 |
| 1 | Charlie | 8000 |
| 1 | Diana | 8000 |
Code Environment
Sign in or try as guest to run your code.
Essential
SQL 0/33
Spark 0/20
Snowflake 0/22
Python 0/24
Need more practice in this area? Explore more questions →
Amazon
Revolut
Accenture
Adobe
Google
LinkedIn
Samsung
Datadog
Wix
Dropbox
Meta
OpenAI
Hulu
Uber
X
DoorDash
Anthropic
ActivisionBlizzard
Vercel
Crypto.Com
Zscaler
DeutscheBank
Apple
GoDaddy
GitLab
BMW
PayPal
Snowflake
AMD
Twilio
Atlassian
JPMorgan
NVIDIA
IBM
Databricks
Coinbase
Cisco
Robinhood
Twitter
Microsoft
Palantir
Netflix
VMware
Cloudflare
Stripe
Lyft
Salesforce
GitHub
Bloomberg
Airbnb
Walmart
SAP
HashiCorp
Instacart
Mastercard
Intel
Visa
Tesla