OkBublewrap

대여 횟수가 많은 자동차들의 월별 대여 횟수 구하기 본문

개발/SQL

대여 횟수가 많은 자동차들의 월별 대여 횟수 구하기

옥뽁뽁 2025. 1. 15. 00:59

대여 횟수가 많은 자동차들의 월별 대여 횟수 구하기

문제

  1. 2022년 8월부터 2022년 10월까지 총 대여 횟수가 5회 이상인 자동차
  2. 월별 자동차 ID별 총 대여 횟수
  3. 월 기준 오름차순, 자동차 ID 내림차순
  4. 특정 월의 총 대여 횟수가 0인 경우 결과에서 제외

입력 테이블

  1. CAR_RENTAL_COMPANY_RENTAL_HISTORY
    • HISTORY_ID
    • CAR_ID
    • START_DATE
    • END_DATE

풀이

1. 해당 기간 총 대여 횟수가 5회 이상인 자동차 ID 구하기

  1. start_date가 해당 기간 사이에 있는 car_id 구하기
  2. car_id가 5개 이상인 car_id만 구하기
select car_id
from CAR_RENTAL_COMPANY_RENTAL_HISTORY 
where start_date between '2022-08-01' and '2022-10-31'
group by car_id
having count(*) >= 5

2. 해당 기간동안의 월별 자동차 ID별 총 대여 횟수 구하기

  1. car_id 중 다른월도 있을 수 있으므로 한번 더 필터링
  2. 월별, car_id별 집계
select month(start_date) as MONTH, car_id, count(*) as RECORDS
from CAR_RENTAL_COMPANY_RENTAL_HISTORY
where car_id in
(
   select car_id
   from CAR_RENTAL_COMPANY_RENTAL_HISTORY 
   where start_date between '2022-08-01' and '2022-10-31'
   group by car_id
   having count(*) >= 5
)
and
start_date BETWEEN '2022-08-01' AND '2022-10-31'

3. 정렬 및 전체 코드

select month(start_date) as MONTH, car_id, count(*) as RECORDS
from CAR_RENTAL_COMPANY_RENTAL_HISTORY
where car_id in
(
    select car_id
    from CAR_RENTAL_COMPANY_RENTAL_HISTORY 
    where start_date between '2022-08-01' and '2022-10-31'
    group by car_id
    having count(*) >= 5
)
and
start_date BETWEEN '2022-08-01' AND '2022-10-31'
group by month(start_date), car_id
order by month(start_date) asc, car_id desc