TIL/SQL

TIL (7/17) <if문, 임시테이블>

jojoon2786 2024. 7. 17. 15:33

 

1. if문

select car_id, if(max(if(start_date <= '2022-10-16' and end_date >= '2022-10-16', 1, 0))=0, '대여 가능', '대여중') as AVAILABILITY
from CAR_RENTAL_COMPANY_RENTAL_HISTORY
group by 1
order by 1 DESC

## if 문 기본 구조

if(조건, 조건이 참일경우 실행, 조건이 거짓일경우 실행)

 

2. 임시테이블

with temp1 as(
select car_id,
          case when start_date <= '2022-10-16' and end_date >= '2022-10-16' then 1
          else 0 end as abailability
from car_rental_company_rental_history)

select car_id, if(max(abailability) = 1, '대여중', '대여 가능') as abailability2
from temp1
group by car_id
order by car_id desc

## 임시테이블 기본 구조

with {임시테이블명} as (서브쿼리) > 본 쿼리 위쪽에 써줌.

 

with절은 동일한 SQL이 반복되어서 사용될 때 성능을 높이기 위해 사용된다.

table을 만들지 않고도 table 만든 것과 같은 효과를 내는데, 실제로는 temp라는 임시 테이블에 저장되는 것이다.