2024.06.19 TIL - SQL 강의 (조건문 if, case 예시 모음)

Innes·2024년 6월 19일
0

TIL(Today I Learned)

목록 보기
136/147
post-thumbnail

조건문 (if)

1. if문 예시 (1)

select restaurant_name,
       cuisine_type "원래 음식 타입",
       if(cuisine_type='Korean', '한식', '기타') "음식 타입"
from food_orders
  • cuisine_type 컬럼의 값이 Korean인 경우 컬럼 값을 '한식'으로, Korean이 아닌 경우는 '기타'라고 보여줘.
  • if(조건, 조건 충족할 때, 조건 충족 못 할 때)

2. if문 예시 (2)

select addr "원래 주소",
       if(addr like '%평택군%', replace(addr, '문곡리', '문가리'), addr) "바뀐 주소"
from food_orders
where addr like '%문곡리%'

3. if문 예시 (3)

select substring(if(email like '%gmail%', replace(email, 'gmail', '@gmail'), email), 10) "이메일 도메인",
       count(customer_id) "고객 수",
       avg(age) "평균 연령"
from customers
group by 1

조건문 (case)

  • 여러가지 조건을 줘야 할 때 유용
  • 키워드 : case, when, then, else, end
  1. case문 예시 (1)
SELECT case when cuisine_type='Korean' then '한식'
			when cuisine_type in ('Japanese', 'Chinese') then '아시아'
			else '기타' END '음식타입',
			cuisine_type 
from food_orders 

// else 조건 줄 값이 없다면 생략 가능

  1. case문 예시 (2)
select order_id,
       price,
       quantity,
       case when quantity=1 then price
            when quantity>=2 then price/quantity end "음식 단가"
from food_orders

  1. case문 예시 (3)
select restaurant_name,
       addr,
       case when addr like '%경기도%' then '경기도'
            when addr like '%특별%' or addr like '%광역%' then substring(addr, 1, 5)
            else substring(addr, 1, 2) end "변경된 주소"
from food_orders

  1. case문 예시 (4)
SELECT 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대 여성' end '고객분류',
		name,
		age,
		gender
from customers 
where age BETWEEN 10 and 29
profile
꾸준히 성장하는 우상향 개발자

0개의 댓글