1633. Percentage of Users Attended a Contest : leetcode

오유찬·2025년 12월 3일

SQL

목록 보기
16/71
# combine Users table and Distinct contest_id
SELECT u.user_id, r.contest_id
FROM Users u CROSS JOIN 
    (SELECT DISTINCT contest_id FROM Register) as r
user_idcontest_id
7215
2215
6215
7209
2209
6209
7208
2208
6208
7210
2210
6210
7207
2207
6207
# combine with Register table including NULL
SELECT u.user_id, c.contest_id, r.user_id
FROM Users u CROSS JOIN 
    (SELECT DISTINCT contest_id FROM Register) as c
LEFT JOIN Register r 
    ON u.user_id = r.user_id AND r.contest_id = c.contest_id;
user_idcontest_iduser_id
72157
2215null
62156
72097
22092
62096
72087
22082
62086
72107
22102
62106
7207null
22072
6207null

answer

SELECT  c.contest_id, 
        ROUND((SUM(CASE WHEN r.user_id IS NOT NULL THEN 1
        ELSE 0 END) / COUNT(*) * 100), 2) as percentage
FROM Users u CROSS JOIN 
    (SELECT DISTINCT contest_id FROM Register) as c
LEFT JOIN Register r 
    ON u.user_id = r.user_id AND r.contest_id = c.contest_id
GROUP BY c.contest_id
ORDER BY percentage DESC, c.contest_id ASC;
contest_idpercentage
208100
209100
210100
21566.67
20733.33

better answer

SELECT  contest_id,
        ROUND(
            COUNT(DISTINCT user_id ) * 100 / (SELECT COUNT(user_id) FROM Users), 2
        ) AS percentage
FROM
    Register
GROUP BY
    contest_id
ORDER BY
    percentage DESC,
    contest_id;
profile
열심히 하면 재밌다

0개의 댓글