[Leetcode] 1633.Percentage of Users Attended a Contest

Sooin Yoon·2025년 4월 23일

링크텍스트
+-------------+---------+
| Column Name | Type |
+-------------+---------+
| user_id | int |
| user_name | varchar |
+-------------+---------+
user_id is the primary key (column with unique values) for this table.
Each row of this table contains the name and the id of a user.

Table: Register

+-------------+---------+
| Column Name | Type |
+-------------+---------+
| contest_id | int |
| user_id | int |
+-------------+---------+
(contest_id, user_id) is the primary key (combination of columns with unique values) for this table.
Each row of this table contains the id of a user and the contest they registered into.

Write a solution to find the percentage of the users registered in each contest rounded to two decimals.

Return the result table ordered by percentage in descending order. In case of a tie, order it by contest_id in ascending order.

The result format is in the following example.

이 문제에서 헷갈렸던 부분이 각 contest에 대해 몇명이 참여하는지에 대한 퍼센테지를 구하는건데 contest_id를 COUNT를 해서 100을 곱하는것 까지는 수월했지만 user_id를 몇명으로 나누어야 되는지 부분이 좀 헷갈려서 sum(user_id)를 해서 모든 숫자가 더해져 버렸음

최종답!

with total_users AS (
    SELECT COUNT(*) AS total
    FROM Users
)
SELECT contest_id, ROUND((COUNT(*)*100)/t.total, 2) AS percentage
FROM Register r
JOIN total_users t
GROUP BY contest_id
ORDER BY percentage DESC, contest_id ASC

0개의 댓글