1. 程式人生 > 其它 >1633. 各賽事的使用者註冊率(SQL)

1633. 各賽事的使用者註冊率(SQL)

技術標籤:databaseleetcode easyleetcode

題目:https://leetcode-cn.com/problems/percentage-of-users-attended-a-contest/

使用者表:Users

+-------------+---------+
| Column Name | Type |
+-------------+---------+
| user_id | int |
| user_name | varchar |
+-------------+---------+
user_id 是該表的主鍵。
該表中的每行包括使用者 ID 和使用者名稱。

登錄檔:Register

+-------------+---------+
| Column Name | Type |
+-------------+---------+
| contest_id | int |
| user_id | int |
+-------------+---------+
(contest_id, user_id) 是該表的主鍵。
該表中的每行包含使用者的 ID 和他們註冊的賽事。

寫一條 SQL 語句,查詢各賽事的使用者註冊百分率,保留兩位小數。

返回的結果表按percentage的降序排序,若相同則按contest_id的升序排序。

查詢結果如下示例所示:

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 |
+------------+---------+

結果表:
+------------+------------+
| contest_id | percentage |
+------------+------------+
| 208 | 100.0 |
| 209 | 100.0 |
| 210 | 100.0 |
| 215 | 66.67 |
| 207 | 33.33 |
+------------+------------+
所有使用者都註冊了 208、209 和 210 賽事,因此這些賽事的註冊率為 100% ,我們按 contest_id 的降序排序加入結果表中。
Alice 和 Alex 註冊了 215 賽事,註冊率為 ((2/3) * 100) = 66.67%
Bob 註冊了 207 賽事,註冊率為 ((1/3) * 100) = 33.33%

程式碼:

SELECT R.contest_id, round(count(DISTINCT R.user_id) / (SELECT count(*) FROM Users) * 100, 2) as percentage FROM Users U RIGHT JOIN Register R ON U.user_id = R.user_id GROUP BY R.contest_id ORDER BY percentage DESC, contest_id

注意GROUP BY後count都是連線後的數,所以分母要從users表單獨取