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


날짜, 소숫점, 천단위를 표현할 때 사용함
+완벽정리 블로그) https://gent.tistory.com/331
문자열로 바꾸는 건 월을 비교할때 10, 4, 8 이런식으로 10월을 1부터 시작하는것으로 인식해서 정렬이 안된다. 그래서 월을 숫자로 변환해줘서 8 < 10 으로 인식하도록 한다.
between은 >=, <= 이상 이하를 뜻한다.
a between 5 and 10
= a가 5이상 10이하인 데이터
-- -- 코드를 입력하세요
select to_char(a.start_date, 'FMMM') as "month", a.car_id, count(*) as "records"
from CAR_RENTAL_COMPANY_RENTAL_HISTORY a,
(
select car_id, count(*)
from CAR_RENTAL_COMPANY_RENTAL_HISTORY
where to_char(start_date, 'YYYYMM') >= '202208'
and to_char(start_date, 'YYYYMM') <= '202210'
group by CAR_ID
having count(*) >= 5
) b
where a.car_id = b.car_id
group by to_char(a.start_date, 'FMMM'), a.car_id
Having count(*) <> 0
order by to_char(a.start_date, 'FMMM') asc, a.car_id desc
-> 이렇게 짜니까
| month | car_id | recods |
|---|---|---|
| 10 | 1 | 5 |
| 8 | 3 | 3 |
| 9 | 2 | 1 |
month 월이 10 -> 8 -> 9 순서대로 출력된다.
to_char 함수 = 즉 문자열이니까, 당연한 결과이다.
to_number 함수 = 숫자로 바꾸는 함수를 사용했더니 이 부분은 해결되었다.
-- 코드를 입력하세요
select to_number(to_char(a.start_date, 'MM')) as "month", a.car_id, count(*) as "records"
from CAR_RENTAL_COMPANY_RENTAL_HISTORY a
where a.car_id in (
select car_id
from CAR_RENTAL_COMPANY_RENTAL_HISTORY
where start_date BETWEEN to_date('202208', 'YYYYMM') AND to_date('202210', 'YYYYMM')
group by CAR_ID
having count(*) >= 5
)
and a.start_date BETWEEN to_date('202208', 'YYYYMM') AND to_date('202210', 'YYYYMM')
group by to_number(to_char(a.start_date, 'MM')), a.car_id
Having count(*) <> 0
order by 1, 2 desc
-> start_date BETWEEN to_date('202208', 'YYYYMM') AND to_date('202210', 'YYYYMM')
202208과 202210을 날짜화 해서 쿼리를 짜니까 자꾸 틀렸다.
-- 코드를 입력하세요
select to_number(to_char(a.start_date, 'MM')) as "month", a.car_id, count(*) as "records"
from CAR_RENTAL_COMPANY_RENTAL_HISTORY a
where a.car_id in (
select car_id
from CAR_RENTAL_COMPANY_RENTAL_HISTORY
WHERE TO_CHAR(START_DATE, 'YYYY-MM-DD') BETWEEN '2022-08-01' AND '2022-10-31'
group by CAR_ID
having count(*) >= 5
)
and TO_CHAR(START_DATE, 'YYYY-MM-DD') BETWEEN '2022-08-01' AND '2022-10-31'
group by to_number(to_char(a.start_date, 'MM')), a.car_id
Having count(*) <> 0
order by 1, 2 desc
-> TO_CHAR(START_DATE, 'YYYY-MM-DD') BETWEEN '2022-08-01' AND '2022-10-31'
start_date를 문자열로 바꾸어서 비교하니까 정답 처리 되었다.
- 왜 이럴까?



결과도 완전히 다르다.
.......... 우선은 시간이 없으니까 날짜가 나오면 to_char 로 바꾸어서 생각하는걸로 하자.