윈도우 count 함수 활용 문제

HONG LEE ·2024년 7월 1일
0

https://leetcode.com/problems/percentage-of-users-attended-a-contest/description/

위 문제를 윈도우 함수 count를 사용하여 풀어보았습니다.

코드를 입력하세요

WITH cte AS (
    select
        user_id,
        user_name,
        count(user_id) over() as total_num
    from Users
)
    select 
        distinct r.contest_id,
        round(count(r.user_id) over(partition by r.contest_id) / c.total_num *100.0, 2) as percentage
    from Register r
    join cte c on r.user_id = c.user_id
    order by 2 desc, 1

아래는 다른 사람이 작성한 더 효율이 높은 쿼리입니다.

코드를 입력하세요

SELECT r.contest_id, round(count(*) / (SELECT count(*) from Users) * 100 ,2) as percentage
FROM REGISTER r
LEFT JOIN Users u
ON r.user_id = u.user_id
GROUP BY r.contest_id
ORDER BY percentage DESC, r.contest_id ASC

위 사람은 select 문에 서브 select문을 작성하여 풀었습니다. 여기서 유의해야 할 점은 join에 r.user_id = u.user_id를 해주어야 한다는 점입니다.

그리고 윈도우 함수 안에는 distinct문을 함께 못쓴다는 사실 또한 새로 배운점이었습니다.

0개의 댓글