[SQL] group by 사용시 조건 주의 (in.서브쿼리)

도리·2025년 2월 17일

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

나의 틀린 코드

WITH car AS (
    SELECT car_id, 
           MONTH(start_date) AS start_month
    FROM car_rental_company_rental_history
    WHERE start_date >= '2022-08-01' 
      AND start_date < '2022-11-01'
)
SELECT start_month AS month, 
       car_id, 
       COUNT(*) AS records
FROM car
GROUP BY start_month, car_id
HAVING COUNT(*) >= 5
ORDER BY start_month, car_id DESC;

조건에 맞춰 뽑고 그룹화, having 조건으로 5건이상만 찍히게 함.

-> 각 월별 5건 이상만 찍힘..
-> "총 대여 횟수"가 5건 이상이어야 함.

문제 상황

  1. 2022년 8월 1일부터 10월 31일까지의 기록수집,
  2. 각 월별(start_month) 및 차량(car_id)별로 그룹화.
  3. 그 달에 해당 차량의 대여 건수가 5건 이상인 경우만 결과로.

재도전 코드

# 총 대여횟수가 5회 이상인 table 만들기 
with time as (
select car_id, count(*) 
from car_rental_company_rental_history 
where start_date >= '2022-08-01' and start_date < '2022-11-01' 
group by car_id
having count(*) >4
)
select  month(h.start_date)as month , h.car_id, count(*) as records
from time t
inner join car_rental_company_rental_history h on h.car_id = t.car_id
group by car_id , month(h.start_date)
order by month(h.start_date), car_id desc;

근데도 틀림. .
왜냐 서브쿼리에만 날짜 조건을 붙여서.

time에는 2022-08-01~2022-11-01 , 총 대여횟수가 5이상인 car_id가 뽑히는게 맞다.
이때 그냥 "car_id"만 뽑히고 나머지 정보는 사라진다고 봐야한다.

  • 메인쿼리에서는 다른 날짜 즉, 11월이나 7월등의 정보까지 그룹핑되어 나타난다는 것이다...!!

정답코드

# 총 대여횟수가 5회 이상인 table 만들기 
with time as (
select car_id, count(*) 
from car_rental_company_rental_history 
where start_date >= '2022-08-01' and start_date < '2022-11-01' 
group by car_id
having count(*) >4
)
select  month(h.start_date)as month , h.car_id, count(*) as records
from time t
join car_rental_company_rental_history h on h.car_id = t.car_id
where start_date >= '2022-08-01' and start_date < '2022-11-01' 
group by month(h.start_date), car_id
order by month(h.start_date), car_id desc;
profile
인공지능응용학과 졸업

0개의 댓글