CASE
어떤 특정 조건이 충족이 되면 SQL를 실행하기 위해 CASE를 사용한다.
if/else와 유사하다. 아래 [그림 1]처럼 테이블이 있다고 가정해보자.
ID 1~100은 "Premium", 100~200은 "Plus", 나머지는 "Normal"로 지정해주자.
select customer_id,
case
when (customer_id <= 100) then "Premium"
when (customer_id <= 200) then "Plus"
else "Normal"
end as customer_class /*column name*/
from customer
이번에는 customer_id가 2면 "Winner", 5fmf "Second Place"로 나머지는 "Normal"로 지정해주자.
select customer_id,
case
when (customer_id = 2) then "Winner"
when (customer_id = 5) then "Second Place"
else "Normal"
end as customer_class
from customer
아래와 같은 방법으로도 쓸 수 있다.
select rental_rate,
case rental_rate
when 0.99 then 1
else 0
end from film
다른 오퍼레이션과 함께 쓸 수 있다.
아래 [그림 5]는 1을 모두 더한 값이다.
select
sum(case rental_rate
when 0.99 then 1
else 0
end) as number_of_bargins
from film
COALESCE
Null이 아닌 첫 Argument를 도출한다.
- 모든 argument가 Null이면 COALESCE도 Null이 도출된다.
- Null 값을 가진 표를 쿼리할 때 유용
- 예를 들어, integer값 - null은 null로 도출되기 때문에 처리를 해줘야함.
- 원래 표를 건드리지 않는 선에서 활용한다. 왜냐면 Null값이 있다는 것에도 이유가 있기 때문에 오퍼레이션 계산에 사용한다.
e.g.
select coalesce(1,2) -> 1
select coalesce(null, 2, 3) -> 2
CAST
데이터 유형을 바꾸어준다.
'five' as integer은 안된다.
select cast("5" as integer)
NULLIF
두 개의 값을 넣어서 두 값이 같으면 NULL, 다르면 첫 번째 Argument가 도출된다.
NULL 값이 에러의 원인이 되거나 원하지 않는 결과가 나올 때 사용한다.
우선, 아래 [그림 7]과 같은 표를 만들어보자
'a', 'b' 부서의 비율을 나타내려 한다.
아래 [그림 7]은 department가 'a'인 것들을 합치면 2가 되고, department가 'b'인 것들을 합치면 1이 되는데, 2 / 1 하면 2가 된다.
select
(sum(case when department = "a" then 1 else 0 end)) /
sum(case when department = "b" then 1 else 0 end) as department_ratio
from depts
만약, 'b'가 없다면, 즉 2/0인 경우에는 에러가 발생한다. 그래서 에러대신 NULL을 나오게 하는 방법이 NULLIF이다.
select
(sum(case when department = 'a' then 1 else 0 end))/
nullif(sum(case when department = 'b' then 1 else 0 end), null) as department_ratio
from depts
'Coding Test' 카테고리의 다른 글
SQL - [IMPORT & EXPORT] (0) | 2022.12.17 |
---|---|
SQL - [Table Command] (0) | 2022.12.13 |
SQL - [DB, Table] (0) | 2022.12.13 |
SQL - [고급 SQL] (2) | 2022.12.07 |
SQL - [AS, JOIN, UNION] (0) | 2022.12.07 |