SQL, 이걸로 단권화 완료- 다시 톺아보기 3

아뇨 민균데요·2025년 4월 30일
0


1. 문자 좀 다뤄보자 (REPLACE, SUBSTR, CONCAT)

회사에서 데이터 보면 꼭 이런 경우 있지:

  • 상점 이름이 바뀜 (Blue → Pink)
  • 주소에 필요 없는 동네 이름
  • “서울 음식점” 이런 식으로 묶어야 할 때

이럴 땐 아래 세 개 함수로 해결 가능!

replace(컬럼, 바꿀문자, 바뀔문자)
substr(컬럼, 시작위치, 글자수)
concat(문자1, 문자2, 문자3 ...)

예시:

select restaurant_name "원래",
       replace(restaurant_name, 'Blue', 'Pink') "수정된"
from food_orders
where restaurant_name like '%Blue%'

2. 조건 따라 다르게 처리해보자 (IF, CASE)

엑셀에서 if 쓰듯이 SQL도 똑같이 가능함.

if(조건, 참일 때 값, 거짓일 때 값)

복잡한 경우는 case 문으로!

case when 조건 thenwhen 조건2 then2
     else 기본값
end

예시:

select cuisine_type,
       if(cuisine_type='Korean', '한식', '기타') as 음식타입
from food_orders

3. 문자 다듬고 그룹으로 묶기 (GROUP BY)

서울 지역 음식점들의 음식 타입별 평균 주문금액 구하는 예시:

select substring(addr, 1, 2) "시도",
       cuisine_type "종류",
       avg(price) "평균"
from food_orders
where addr like '%서울%'
group by 1, 2

4. 도메인 분석도 가능하지

이메일 도메인별로 고객 수랑 평균 연령 구하려면 이렇게:

select substring(email, 10) "도메인",
       count(customer_id) "고객 수",
       avg(age) "평균 나이"
from customers
group by 1

5. 유저 세그먼트 만들기 (User Segmentation)

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

6. 수수료 계산도 SQL이 한다

조건문+연산식 다 때려넣기 가능

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

7. 데이터 타입 오류? 당황하지 말자

숫자인 줄 알았는데 문자였다면 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, concat
  • 조건 처리: if, case
  • 그룹 분석: group by + 평균, 갯수
  • 실무 감성: 유저 나누고, 수수료 계산하고, 에러 해결까지 완료

profile
this man을 꿈 속에서 보신 적이 있으신가요?

0개의 댓글