Skip to content

Commit 2427ea0

Browse files
authored
EASY
1 parent 07dc35d commit 2427ea0

File tree

1 file changed

+83
-0
lines changed

1 file changed

+83
-0
lines changed

1633. Percentage of Users Attended a Contest.sql

+83
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,86 @@
1+
-- Problem:
2+
3+
/*
4+
Table: Users
5+
6+
+-------------+---------+
7+
| Column Name | Type |
8+
+-------------+---------+
9+
| user_id | int |
10+
| user_name | varchar |
11+
+-------------+---------+
12+
user_id is the primary key (column with unique values) for this table.
13+
Each row of this table contains the name and the id of a user.
14+
15+
16+
Table: Register
17+
18+
+-------------+---------+
19+
| Column Name | Type |
20+
+-------------+---------+
21+
| contest_id | int |
22+
| user_id | int |
23+
+-------------+---------+
24+
(contest_id, user_id) is the primary key (combination of columns with unique values) for this table.
25+
Each row of this table contains the id of a user and the contest they registered into.
26+
27+
28+
Write a solution to find the percentage of the users registered in each contest rounded to two decimals.
29+
30+
Return the result table ordered by percentage in descending order. In case of a tie, order it by contest_id in ascending order.
31+
32+
The result format is in the following example.
33+
34+
35+
36+
Example 1:
37+
38+
Input:
39+
Users table:
40+
+---------+-----------+
41+
| user_id | user_name |
42+
+---------+-----------+
43+
| 6 | Alice |
44+
| 2 | Bob |
45+
| 7 | Alex |
46+
+---------+-----------+
47+
Register table:
48+
+------------+---------+
49+
| contest_id | user_id |
50+
+------------+---------+
51+
| 215 | 6 |
52+
| 209 | 2 |
53+
| 208 | 2 |
54+
| 210 | 6 |
55+
| 208 | 6 |
56+
| 209 | 7 |
57+
| 209 | 6 |
58+
| 215 | 7 |
59+
| 208 | 7 |
60+
| 210 | 2 |
61+
| 207 | 2 |
62+
| 210 | 7 |
63+
+------------+---------+
64+
Output:
65+
+------------+------------+
66+
| contest_id | percentage |
67+
+------------+------------+
68+
| 208 | 100.0 |
69+
| 209 | 100.0 |
70+
| 210 | 100.0 |
71+
| 215 | 66.67 |
72+
| 207 | 33.33 |
73+
+------------+------------+
74+
Explanation:
75+
All the users registered in contests 208, 209, and 210. The percentage is 100% and we sort them in the answer table by contest_id in ascending order.
76+
Alice and Alex registered in contest 215 and the percentage is ((2/3) * 100) = 66.67%
77+
Bob registered in contest 207 and the percentage is ((1/3) * 100) = 33.33%
78+
*/
79+
80+
-------------------------------------------------------------------------------
81+
82+
-- Solution:
83+
184
SELECT r.contest_id, ROUND((COUNT(DISTINCT r.user_id) / (SELECT COUNT(DISTINCT user_id) FROM Users)) * 100, 2) AS percentage
285
FROM Users u
386
GROUP BY r.contest_id

0 commit comments

Comments
 (0)