2024.06.25 TIL - SQL 강의 (조건문 심화, 데이터타입 변환)

Innes·2024년 6월 25일
0

TIL(Today I Learned)

목록 보기
137/147
post-thumbnail

조건문에서 서로 다른 식 적용하기 (수수료)

1. 지역과 배달시간을 기반으로 배달수수료 구하기 (식당 이름, 주문 번호 함께 출력)

(지역 : 서울, 기타 - 서울일 때는 수수료 계산 * 1.1, 기타일 때는 곱하는 값 없음
시간 : 25분, 30분 - 25분 초과하면 음식 가격의 5%, 30분 초과하면 음식 가격의 10%)

SELECT case when delivery_time > 30 then price * 0.1 * if(addr like '%서울%', 1.1, 1)
			when delivery_time > 25 then price * 0.05 * if(addr like '%서울%', 1.1, 1)
			else 0 end "수수료",
		restaurant_name ,
		order_id ,
		price ,
		delivery_time ,
		addr 
from food_orders 

2.주문 시기와 음식 수를 기반으로 배달할증료 구하기

(주문 시기 : 평일 기본료 = 3000 / 주말 기본료 = 3500
음식 수 : 3개 이하이면 할증 없음 / 3개 초과이면 기본료 * 1.2)

SELECT case when day_of_the_week='Weekday' then 3000 * if(quantity > 3, 1.2, 1)
			when day_of_the_week='Weekend' then 3500 * if(quantity > 3, 1.2, 1)
			end "배달 할증료",
		restaurant_name ,
		order_id ,
		day_of_the_week ,
		quantity 
from food_orders 

데이터 타입 변환 (숫자 <-> 문자)

  • decimal : 숫자로 변경
  • char : 문자로 변경
--숫자로 변경
cast(if(rating='Not given', '1', rating) as decimal) 

--문자로 변경
concat(restaurant_name, '-', cast(order_id as char))
profile
꾸준히 성장하는 우상향 개발자

0개의 댓글