💻 SQL 고득점 Kit > GROUP BY > 문제
✏️ 풀이
CASE WHEN
을 사용하여 새로운 열을 생성한다
CASE
WHEN 조건식(기존열 = 조건) THEN '값'
...
ELSE '값'
END AD 새로운 열
- 서브쿼리를 사용하여 대여중인
CAR_ID
를 구한다
- 해당
CAR_ID
에 모두 대여중
을 넣어주어야 한다
- 그렇지 않으면
(29, '대여중')
, (29, '대여 가능')
이 모두 생긴다
DISTINCT
또는 GROUP BY
를 사용하여 중복을 제거한다
ORDER BY
를 사용하여 정렬한다
👉 제출 코드
MySQL
SELECT CAR_ID,
CASE
WHEN CAR_ID IN (SELECT CAR_ID
FROM CAR_RENTAL_COMPANY_RENTAL_HISTORY
WHERE '2022-10-16' BETWEEN START_DATE AND END_DATE)
THEN '대여중'
ELSE '대여 가능'
END AS AVAILABILITY
FROM CAR_RENTAL_COMPANY_RENTAL_HISTORY
GROUP BY CAR_ID
ORDER BY CAR_ID DESC
SELECT DISTINCT CAR_ID,
CASE
WHEN CAR_ID IN (SELECT CAR_ID
FROM CAR_RENTAL_COMPANY_RENTAL_HISTORY
WHERE '2022-10-16' BETWEEN START_DATE AND END_DATE)
THEN '대여중'
ELSE '대여 가능'
END AS AVAILABILITY
FROM CAR_RENTAL_COMPANY_RENTAL_HISTORY
ORDER BY CAR_ID DESC
Oracle
SELECT CAR_ID,
CASE
WHEN CAR_ID IN (SELECT CAR_ID
FROM CAR_RENTAL_COMPANY_RENTAL_HISTORY
WHERE '2022-10-16'
BETWEEN TO_CHAR(START_DATE, 'YYYY-MM-DD') AND TO_CHAR(END_DATE, 'YYYY-MM-DD'))
THEN '대여중'
ELSE '대여 가능'
END AS AVAILABILITY
FROM CAR_RENTAL_COMPANY_RENTAL_HISTORY
GROUP BY CAR_ID
ORDER BY CAR_ID DESC