본문 바로가기
MySQL

[MySQL] case, if 사용하기

by coding_su 2022. 12. 7.

📝MySQL Workbench case, if 함수 사용하기

※ 새로운 컬럼 추가할때는 select * , 콤마 찍어주기

 

case

※ case와 end는 한쌍이며 select 아래 위치, when - then은 항상 같이 사용

 else는 모든 조건이 True가 아닌 경우 else의 결과값을 반환한다(else가 없으면 null 반환)

-- 년도가 2000년 이상이면 'Modern Book' 이라고 하고
-- 그렇지 않으면 '20th Book' 이라고 새로운 컬럼 Genre 를 만들기

-- 1. case문으로 처리하는 방법

select * ,
	case 
		when released_year >= 2000 then 'Modern Book'
        else '20th Book'
    end as 'Genre'
from books;

-- 재고가 0~50이면 *, 51~100이면 **, 101~150이면 ***,
-- 그렇지않으면 ****로 표시하는 컬럼 stock이라는 컬럼을 만들기

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

-- ex)

select title,author_lname,
	case 
		when title like '%stories%' then 'Short Stories'
        when title like '%just kids%' or title like 'A Heartbreaking work%' then 'Memoir'
        else 'Novel'
    end as 'TYPE'
from books;

 

if

※ 조건입력, 트루일때의 값, 그렇지 않을때의 값 입력(이렇게 조건이 2가지일때만 가능하다)

-- 2. if 함수로 처리하는 방법

select * ,
if(released_year >= 2000, 'Modern Book', '20th Book') as 'Genre'
from books;

-- ex)

select title, author_lname,
	if(count(title) = 1, '1 book', concat(count(title), ' books')) as 'COUNT'
from books
group by author_lname
order by author_lname;

 

댓글