Percentage of Users Attended a Contest
Task: Find the percentage of users registered in each contest rounded to 2 decimals. Return sorted by percentage descending, then contest_id ascending.
Table: Users
| Column Name | Type |
|---|---|
| user_id | INT |
| user_name | varchar(20) |
Table: Register
| Column Name | Type |
|---|---|
| contest_id | INT |
| user_id | INT |
Input: Users table:
| user_id | user_name |
|---|---|
| 6 | Alice |
| 2 | Bob |
| 7 | Alex |
Register table:
| 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 |
View Reference Solution & Explanation ▼
This solution uses the `GROUP BY` clause to aggregate results, the `ROUND()` function to format numerical output, and a subquery as a derived table or inline value.
SELECT contest_id, ROUND(COUNT(user_id) * 100.0 / (SELECT COUNT(*) FROM Users), 2) AS percentage FROM Register GROUP BY contest_id ORDER BY percentage DESC, contest_id ASC;