40. Contest Participation Rate
An online contest platform tracks user registrations for various contests. The analytics team wants to determine how popular each contest is by calculating what percentage of total users participated in each one.
Two tables are provided:
Users:
ββββββββββββ¦βββββββββββββ β Column β Type β β βββββββββββ¬βββββββββββββ£ β user_id β int β β user_nameβ varchar β ββββββββββββ©βββββββββββββ
- user_id: Unique identifier for each user.
- user_name: Name of the user.
Register:
ββββββββββββββ¦βββββββββββ β Column β Type β β βββββββββββββ¬βββββββββββ£ β contest_id β int β β user_id β int β ββββββββββββββ©βββββββββββ
- contest_id: Unique identifier for each contest.
- user_id: ID of the user who registered for the contest.
- (contest_id, user_id) is the primary key (combination of columns with unique values).
Write an SQL query to report the contest_id and the percentage of users registered for each contest, rounded to 2 decimal places. Sort the result by percentage in descending order, and in case of a tie, by contest_id in ascending order.
Example 1:
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.0 β β 209 β 100.0 β β 210 β 100.0 β β 215 β 66.67 β β 207 β 33.33 β ββββββββββββββ©βββββββββββββ
Explanation:
- Total users = 3
- Contest 208: 3 users β (3/3) Γ 100 = 100.00%
- Contest 209: 3 users β (3/3) Γ 100 = 100.00%
- Contest 210: 3 users β (3/3) Γ 100 = 100.00%
- Contest 215: 2 users β (2/3) Γ 100 = 66.67%
- Contest 207: 1 user β (1/3) Γ 100 = 33.33%
Still unsure what the problem is asking ?
Letβs go through a few more examples, step by step, to make it clearer.