
회사에서 데이터 보면 꼭 이런 경우 있지:
이럴 땐 아래 세 개 함수로 해결 가능!
replace(컬럼, 바꿀문자, 바뀔문자)
substr(컬럼, 시작위치, 글자수)
concat(문자1, 문자2, 문자3 ...)
예시:
select restaurant_name "원래",
replace(restaurant_name, 'Blue', 'Pink') "수정된"
from food_orders
where restaurant_name like '%Blue%'
엑셀에서 if 쓰듯이 SQL도 똑같이 가능함.
if(조건, 참일 때 값, 거짓일 때 값)
복잡한 경우는 case 문으로!
case when 조건 then 값
when 조건2 then 값2
else 기본값
end
예시:
select cuisine_type,
if(cuisine_type='Korean', '한식', '기타') as 음식타입
from food_orders
서울 지역 음식점들의 음식 타입별 평균 주문금액 구하는 예시:
select substring(addr, 1, 2) "시도",
cuisine_type "종류",
avg(price) "평균"
from food_orders
where addr like '%서울%'
group by 1, 2
이메일 도메인별로 고객 수랑 평균 연령 구하려면 이렇게:
select substring(email, 10) "도메인",
count(customer_id) "고객 수",
avg(age) "평균 나이"
from customers
group by 1
10~20대 성별 그룹 나누기:
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대 여자"
end as "그룹"
from customers
where age between 10 and 29
조건문+연산식 다 때려넣기 가능
select restaurant_name, order_id, delivery_time, price, addr,
case
when delivery_time>25 and delivery_time<=30 then price*1.05*(if(addr like '%서울%', 1.1, 1))
when delivery_time>30 then price*1.1*(if(addr like '%서울%', 1.1, 1))
else 0
end as 수수료
from food_orders
숫자인 줄 알았는데 문자였다면 cast()로 타입 바꿔주면 됨.
cast(컬럼 as decimal)cast(컬럼 as char)예시:
select cast(order_id as char)
평일은 25분 이상, 주말은 30분 이상이면 ‘Late’로 표시
select order_id, restaurant_name, day_of_the_week, delivery_time,
case
when day_of_the_week='Weekday' and delivery_time>=25 then 'Late'
when day_of_the_week='Weekend' and delivery_time>=30 then 'Late'
else 'On-time'
end as 지연여부
from food_orders
replace, substr, concatif, casegroup by + 평균, 갯수