MySQL

[MySQL] case

건휘맨 2024. 5. 14. 16:08

case와 end는 한쌍

select 아래 위치에 위치하며 when, then은 항상 같이 사용

else는 모든 조건이 True가 아닌 경우 else의 결과값 반환

end as '컬럼 이름' 으로 끝에 컬럼을 생성하고 값을 반환

 

-- 출판년도가 2000년 이상인 책들은 '최신책' 이라고 하고
-- 그렇지 않은 책들은 '예전책' 이라고 하며
-- type 컬럼을 만들자

select *,
	case
		when released_year >= 2000 then '최신책'
		else '예전책'
    end as type
from books;

 

-- 재고가 0 이상이고 50 이하이면 , *
-- 재고가 51 이상이고 100 이하이면 , **
-- 이도 저도 아니면 , ***
-- stock 이라는 컬럼을 만들자.

select *,
	case
		when stock_quantity between 0 and 50 then '*'
       		when stock_quantity >= 51 and stock_quantity <= 100 then '**'
       		else '***'
    end as stock
from books;

-- when stock_quantity between 0 and 50 then '*'
-- when stock_quantity >= 51 and stock_quantity <= 100 then '**'
-- 두 개는 같은 의미