Percentage of Users Attended a Contest
Preview mode. Log in to edit, run, submit, and save progress.
Description
You have two tables: Users and Register. The Register table records which users signed up for which contests. Write a SQL query to find the percentage of users registered in each contest, rounded to 2 decimal places. Return the result ordered by percentage descending. If there is a tie, order by contest_id ascending. (contest_id, user_id) is the primary key.
Database Schema
Users
| Column Name | Type | Description |
|---|---|---|
| user_id | INT | Primary key |
| user_name | VARCHAR | User name |
Register
| Column Name | Type | Description |
|---|---|---|
| contest_id | INT | Contest identifier |
| user_id | INT | FK to Users |
Example
Users
| user_id | user_name |
|---|---|
| 6 | Alice |
| 2 | Bob |
| 7 | Alex |
Register
| contest_id | user_id |
|---|---|
| 215 | 6 |
| 209 | 2 |
| 208 | 2 |
| 210 | 6 |
| 208 | 6 |
| 209 | 7 |
| 209 | 6 |
| 215 | 7 |
| 208 | 7 |
| 210 | 2 |
| 207 | 2 |
| 210 | 7 |
Output
| contest_id | percentage |
|---|---|
| 208 | 100 |
| 209 | 100 |
| 210 | 100 |
| 215 | 66.67 |
| 207 | 33.33 |
Explanation:
Contests 208, 209, 210 had all 3 users (100%). Contest 215 had 2/3 users (66.67%). Contest 207 had 1/3 users (33.33%).
Approach hint
Start with a simple approach, explain the trade-off, then move toward a cleaner or more scalable solution.
Common mistake
Skipping assumptions, edge cases, or trade-offs can make an otherwise good answer feel incomplete.
Users
| user_id | user_name |
|---|---|
| 6 | Alice |
| 2 | Bob |
| 7 | Alex |
Register
| contest_id | user_id |
|---|---|
| 215 | 6 |
| 209 | 2 |
| 208 | 2 |
| 210 | 6 |
| 208 | 6 |
| 209 | 7 |
| 209 | 6 |
| 215 | 7 |
| 208 | 7 |
| 210 | 2 |
| 207 | 2 |
| 210 | 7 |
Output
| contest_id | percentage |
|---|---|
| 208 | 100 |
| 209 | 100 |
| 210 | 100 |
| 215 | 66.67 |
| 207 | 33.33 |