[프로그래머스] SQL - 대여 횟수가 많은 자동차들의 월별 대여 횟수 구하기

장우솔·2023년 8월 25일
0

알고리즘

목록 보기
20/21

https://school.programmers.co.kr/learn/courses/30/lessons/151139

문제
CAR_RENTAL_COMPANY_RENTAL_HISTORY 테이블에서 대여 시작일을 기준으로 2022년 8월부터 2022년 10월까지 총 대여 횟수가 5회 이상인 자동차들에 대해서 해당 기간 동안의 월별 자동차 ID 별 총 대여 횟수(컬럼명: RECORDS) 리스트를 출력하는 SQL문을 작성해주세요. 결과는 월을 기준으로 오름차순 정렬하고, 월이 같다면 자동차 ID를 기준으로 내림차순 정렬해주세요. 특정 월의 총 대여 횟수가 0인 경우에는 결과에서 제외해주세요.

틀린코드

SELECT month(start_date) as month, car_id, count(history_id) as records
from CAR_RENTAL_COMPANY_RENTAL_HISTORY
where car_id in (select car_id from CAR_RENTAL_COMPANY_RENTAL_HISTORY where start_date>="2022-08-01" and start_date<"2022-11-01" group by car_id having count(history_id)>4) 
group by month, car_id
having records >0
order by month, car_id desc

정답

SELECT month(start_date) as month, car_id, count(history_id) as records
from CAR_RENTAL_COMPANY_RENTAL_HISTORY
where start_date>="2022-08-01" and start_date<"2022-11-01" and car_id in (select car_id from CAR_RENTAL_COMPANY_RENTAL_HISTORY where start_date>="2022-08-01" and start_date<"2022-11-01" group by car_id having count(history_id)>4) 
group by month, car_id
having records >0
order by month, car_id desc

틀린 이유
서브쿼리 말고 메인 쿼리에 날짜 조건문 안붙여서!!!!!
서브쿼리에서 바꿔놨는데 왜틀릴까!!!!
--> 서브쿼리에만 날짜 조건문을 붙일 시, 만약 8~10월 사이에 5건 이상이 존재하고 7월에도 대여건이 존재한다면 결과값으로 7월에 해당하는 대여건까지 나온다.

  • date_format 함수와 between을 사용해서도 날짜를 분리할 수 있다.
    ex) where date_format(start_date, "%Y-%m") between '2022-08' and '2022-10'
profile
공부한 것들을 정리하는 블로그

0개의 댓글