본문 바로가기

DB/Programmers SQL Kit

[My_SQL] 대여 기록이 존재하는 자동차 리스트 구하기

문제

 

10월 중에 대여를 시작한 세단의 car_id를 내림차순으로 정렬하는 문제이다.

해당 문제를 풀기 위해서는 

1. distinct

2. DATE_FORMAT

3. in

세 예약어를 알아야한다. 

CAR_RENTAL_COMPANY_RENTAL_HISTORY 에서 10월 중에 대여를 시작한 차를 중복없이 출력하고

해당 car_id를 가지면서 차 종류가 세단인 차량의 car_id를 CAR_RENTAL_COMPANY_CAR 테이블에서 출력한다.

코드

select car_id
from CAR_RENTAL_COMPANY_CAR
where car_type = '세단' and
car_id in (select distinct ch.car_id
    from CAR_RENTAL_COMPANY_RENTAL_HISTORY ch
    where ch.start_date between DATE_FORMAT('2022-10-01', '%Y-%m-%d') and DATE_FORMAT         ('2022-10-31', '%Y-%m-%d'))
order by car_id desc;