SQL 알고리즘 코드카타

SQL 알고리즘 코드카타 24일차(1) 26.01.22(목)

nom_de_plume 2026. 1. 22. 10:47

부제:

특정 기간동안 대여 가능한 자동차들의 대여비용 구하기, 레벨 5

 

1. 문제 링크:https://school.programmers.co.kr/learn/courses/30/lessons/157339
2. 정답 코드: 

select
    cc.car_id,
    cc.car_type,
    round(cc.daily_fee* 30 * (1- dp.discount_rate/100)) as fee
from car_rental_company_car as cc
join car_rental_company_discount_plan as dp
    on cc.car_type = dp.car_type 
        and dp.duration_type = "30일 이상"
where cc.car_type in ("세단","SUV")
    and car_id not in (
        select car_id
        from car_rental_company_rental_history
        where start_date <= "2022-11-30" and end_date >= "2022-11-01"
    )
group by cc.car_id
having fee >= 500000 and fee < 2000000
order by 
    fee desc,
    cc.car_type asc,
    cc.car_id desc


3. 오류 상황:

select
    cc.car_id,
    rh.car_type,
    round(cc.daily_fee* 30 * (1- dp.discount_rate/100),0) as fee
from car_rental_company_car as cc
join car_rental_company_rental_history as rh
    on cc.car_id = rh.car_id
join car_rental_company_discount_plan as dp
    on cc.car_type = dp.car_type
where cc.car_type in ("세단","SUV")
    and rh.end_date between "2022-11-01" and "2022-11-30"
    and dp.duration_type = "30일 이상" 
order by 
    fee desc,
    cc.car_type asc,
    cc.car_id desc

=> JOIN 오용

=> 날짜 설정 오류

=> 금액 조건 누락


4. 시도 방법:

=> 테이블 모두 연결하지 않고 필터링으로 사용

=> NOT IN 사용

=> GROUP BY, HAVING 절 사용


5. 최종 문제 해결 방법:

=> CAR_RENTAL_COMPANY_RENTAL_HISTORY를 JOIN 하면 한 자동차에 대여 기록이 10개 있다면 결과값도 10줄로 늘어나게 된다. 이 문제에서 rh 테이블은 '이 차가 11월에 빌릴 수 있는가?'를 확인하는 필터링 용도로만 써야 한다. JOIN 대신 WHERE 절 안의 서브쿼리에서 사용

=> rh.end_date between ...은 "11월에 반납한 기록이 있는 차"만 가져오게 된다. 11월 1일부터 30일까지 아무 기록이 없는(즉, 대여 가능한) 차는 아예 결과에서 제외된다. 반대로 11월 15일에 반납하고 11월 20일에 또 빌린 차가 있다면, 이 차는 11월에 대여가 불가능한데도 결과에 포함될 수 있다. "11월 1일 ~ 11월 30일" 사이에 대여 중인 모든 기록을 찾아서, 그 기록에 해당하는 CAR_ID를 NOT IN 으로 통째로 빼버려야 한다.

=> 문제에서 요구한 '50만원 이상 200만원 미만' 조건이 쿼리에 누락되었다. SELECT 문에서 계산한 fee를 기준으로 필터링을  GROUP BY 절, HAVING 절을 활용해 작