[MySQL] 조건에 따라 연산을 하는 방법 : IF, CASE

정재현·2024년 1월 2일

MySQL

목록 보기
10/18
post-thumbnail

조건에 따라 연산하는 방법

IF

사용 방법

	if(조건, 조건을 충족할 때, 조건을 충족하지 못할 때)

예시

	select restaurant_name,
		cuisine_type "원래 음식 종류",
		if(cuisine_type='Korean', '한식', '기타') "음식 타입"
	from food_orders

Case When End

  • 범주별로 다른 연산(계산, 문자 바꾸기 등)을 수행하는 방법
    • 범주별로 값을 구할 때 사용하는 group by와 비슷
    • 조건을 여러가지 지정 가능한 조건문
    • 새로운 분류, 카테고리, 유저그룹 등을 만들 때 유용하게 사용 가능

사용 방법

  • else문의 경우 생략 가능
	case when 조건1 then 값(수식)1
		when 조건2 then 값(수식)2
		else 값(수식)3
	end

예시

	select order_id,
		price,
		quantity,	// 별점
		case when quantity=1 then price
			when quantity>=2 then price/quantity 
        end as "음식 단가"
	from food_orders

예시2

	select name,
	age,
	gender,
	case when (age between 10 and 19) and gender='male' then "10대 남자"
		when (age between 10 and 19) and gender='female' then "10대 여자"
		when (age between 20 and 29) and gender='male' then "20대 남자"
		when (age between 20 and 29) and gender='female' then "20대 여자"
		when (age between 30 and 39) and gender='male' then "30대 남자"
		when (age between 30 and 39) and gender='female' then "30대 여자" 
        end "그룹"
	from customers
	where age between 10 and 39

조건문 활용

조회한 데이터가 상식적이지 않은 값을 가지고 있는 경우

상식적이지 않는 데이터

  • ex. 결제 내역이 미래이거나 엄청 과거인 경우

해결 방법

  • 조건문(case when else 문)으로 값의 범위 지정하기
profile
공부 기록 보관소

0개의 댓글