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건 이상이어야 함.
# 총 대여횟수가 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;