--
SELECT MONTH(START_DATE) AS MONTH, CAR_ID, COUNT(*) AS RECORDS
FROM CAR_RENTAL_COMPANY_RENTAL_HISTORY
WHERE MONTH(START_DATE) IN (8,9,10) AND
CAR_ID IN (
SELECT CAR_ID
FROM CAR_RENTAL_COMPANY_RENTAL_HISTORY
WHERE MONTH(START_DATE) IN (8, 9, 10)
GROUP BY CAR_ID
HAVING COUNT(*) >= 5
)
GROUP BY MONTH, CAR_ID
HAVING RECORDS > 0
ORDER BY MONTH ASC, CAR_ID DESC
;
SQL
복사
# CASE : MYSQL
YEAR(날짜 형식의 값)
MONTH(날짜 형식의 값)
DAY(날짜 형식의 값)
DATE_FORMAT(START_DATE, '%c') MONTH
SQL
복사
SELECT MONTH(START_DATE) AS MONTH, CAR_ID, COUNT(*) AS RECORDS
FROM (
SELECT CAR_ID, START_DATE, COUNT(*) OVER (PARTITION BY CAR_ID) AS CAR_COUNT
FROM CAR_RENTAL_COMPANY_RENTAL_HISTORY
WHERE MONTH(START_DATE) IN (8, 9, 10)
) AS t
WHERE CAR_COUNT >= 5
GROUP BY MONTH, CAR_ID
HAVING RECORDS > 0
ORDER BY MONTH ASC, CAR_ID DESC;
SQL
복사
위의 쿼리에서는 WINDOW 함수인 COUNT(*) OVER (PARTITION BY CAR_ID)를 사용하여 CAR_ID 별로 COUNT(*)를 계산합니다. 이를 CAR_COUNT라는 별칭으로 지정합니다. 그런 다음 외부 쿼리에서는 CAR_COUNT가 5 이상인 경우에 대해서만 결과를 반환합니다.