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.

Hints

0
Β 
Test Case

Input:

Users
Register