10세 이상, 30세 미만의 고객의 나이와 성별로 그룹 나누기 (이름도 같이 출력)
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 c
WHERE age BETWEEN 10 AND 29
GROUP BY age, gender ;
[실습] 음식 단가, 음식 종류 별로 음식점 그룹 나누기
select restaurant_name,
price/quantity "단가",
cuisine_type,
order_id,
case when (price/quantity <5000) and cuisine_type='Korean' then '한식1'
when (price/quantity between 5000 and 15000) and cuisine_type='Korean' then '한식2'
when (price/quantity > 15000) and cuisine_type='Korean' then '한식3'
when (price/quantity <5000) and cuisine_type in ('Japanese', 'Chinese', 'Thai', 'Vietnamese', 'Indian') then '아시아식1'
when (price/quantity between 5000 and 15000) and cuisine_type in ('Japanese', 'Chinese', 'Thai', 'Vietnamese', 'Indian') then '아시아식2'
when (price/quantity > 15000) and cuisine_type in ('Japanese', 'Chinese', 'Thai', 'Vietnamese', 'Indian') then '아시아식3'
when (price/quantity <5000) and cuisine_type not in ('Korean', 'Japanese', 'Chinese', 'Thai', 'Vietnamese', 'Indian') then '기타1'
when (price/quantity between 5000 and 15000) and cuisine_type not in ('Korean', 'Japanese', 'Chinese', 'Thai', 'Vietnamese', 'Indian') then '기타2'
when (price/quantity > 15000) and cuisine_type not in ('Korean', 'Japanese', 'Chinese', 'Thai', 'Vietnamese', 'Indian') then '기타3' end "식당 그룹"
from food_orders
지역과 배달시간을 기반으로 배달수수료 구하기 (식당 이름, 주문 번호 함께 출력)
SELECT
CASE WHEN (delivery_time > 30) THEN price*0.1*IF(addr LIKE '%서울%',1.1,1)
-- 위에서 30 초과의 케이스가 모두 걸러졌기 때문에 아래와 같이 하나의 조건만 명시해도 무방함
WHEN (delivery_time > 20) THEN price*0.05
ELSE 0 END "수수료"
, addr
, delivery_time
FROM food_orders fo
주문 시기와 음식 수를 기반으로 배달할증료 구하기
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)
ELSE 'Error' END "배달할증료"
, day_of_the_week
, quantity
FROM food_orders
문자 / 숫자 계산 오류
보이지 않지만 DB에는 데이터 별로 data type이 존재함
숫자처럼 보이지만 문자로 기입되어 있는 경우가 있음
따라서 문자, 숫자를 혼합하여 함수에 사용할 때에는 데이터 타입을 변경해주어야 함
→ CAST 함수 사용!
-- 숫자로 변경
CAST(IF(rating='Not given', '1', rating) AS DECIMAL)
-- 문자로 변경
CONCAT(restaurant_name,'-', CAST(order_id) AS CHAR)