본문 바로가기
[스파르타코딩클럽]데이터분석 과정/SQL

[SQL 코드카다] 89~92번 (LeetCode)

by doo_ 2024. 1. 3.

(89번) managers-with-at-least-5-direct-reports

> 셀프조인에 대한 이해,

SELECT 
    emp1.name -- 4) 매칭된 emp1.이름을 조회한다.
FROM 
    EMPLOYEE emp1 join EMPLOYEE emp2
    on emp1.id = emp2.managerid
    -- 1) emp2.managerid에 해당하는 값에 emp1.id 값이 매칭된다.
group by
    emp1.id, emp1.name --2) 매칭된 emp1.id를 그룹화해서
having
    count(emp2.id) >= 5; -- 3) count를 해서 >= 5인

 

(90번) confirmation-rate

> avg를 응용한 것에 감탄..(원리 이해 중요성을 느꼈다)

SELECT 
    s.user_id, 
    ROUND(IFNULL(AVG(c.action = 'confirmed'), 0),2) as confirmation_rate
    -- action = 'confirmed' 은 true면 1 출력 
FROM
    signups AS s
    LEFT JOIN confirmations c ON s.user_id = c.user_id
    -- 1) confirmation에서 user_id는 외래키 즉 signups의 user_id 값이 없는 경우도 있어 left join.
GROUP BY 
    s.user_id; --2) user_id로 그룹 연산을 하기 위해 그룹화
SELECT
    sig.user_id,
    ROUND(IFNULL(SUM(con.action = 'confirmed')/count(*),0),2) AS confirmation_rate
FROM 
    signups sig
    LEFT JOIN confirmations con
    ON sig.user_id = con.user_id
GROUP BY
    sig.user_id

 

(91번) not-boring-movies

SELECT
    id,
    movie,
    description,
    rating
FROM
    CINEMA
WHERE
    description not in ('boring')
    AND mod(id,2) = 1
ORDER BY
    rating desc