PM부트캠프

팀스파르타 PM과정 (04)

eazy51 2026. 3. 12. 21:05

SQL3강 재수강 + 과제제출, 멤버카드 추가 작성, 내일 면담준비

더보기

오늘의 비극 : 오전 부터 정리하던 블로그글이 4시에 한번 날아가다.....자동저장을 맹신하지 말것,,,,


SQL 챕터3

REPLACE : 특정 문자를 다른 문자로 바꾸기

replace(바꿀 컬럼, 현재 값, 바꿀 값)

LIKE : 문자열의 일부글자 검색

[실습1] 식당 명의 ‘Blue Ribbon’ 을 ‘Pink Ribbon’ 으로 바꾸기

select restaurant_name "원래 상점명",
       replace(restaurant_name, 'Blue', 'Pink') "바뀐 상점명"
from food_orders
where restaurant_name like '%Blue Ribbon%'

[실습2] 주소의 ‘문곡리’ 를 ‘문가리’ 로 바꾸기

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

substring (substr) : 특정 문자만 골라서 조회할 수 있는 기능

substring (조회 할 컬럼, 시작 위치, 글자 수)

select addr "원래 주소",
 substr(addr, 1, 2) "시도"
from food_orders
where addr like '%서울특별시%'

 

concat : 여러 컬럼의 값을 하나로 합칠 수 있는 기능

 concat(붙이고 싶은 값1, 붙이고 싶은 값2, 붙이고 싶은 값3, .....)

 붙일 수 있는 문자종류 : 컬럼,,한글, 영어, 숫자, 기타 특수문자

select restaurant_name "원래 이름",
 addr "원래 주소",
 concat('[', substring(addr, 1, 2), '] ', restaurant_name) "바뀐 이름"
from food_orders
where addr like '%서울%'

[실습3] 서울 지역의 음식 타입별 평균 음식 주문금액 구하기 (출력 : ‘서울’, ‘타입’, ‘평균 금액’)

table : food_orders

서울 : (특정문자기준 분류) substr

지역 : addr

음식 타입별 : cuisine type

평균 : avg

음식 주문금액 : price

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

[실습4 ] 이메일 도메인별 고객 수와 평균 연령 구하기

table : from customers

이메일 도메인 : select substr(email,10) "도메인"

고객수 : count(1) "고객수"

평균연령 : avg(age) "평균연령"

별 : group by 1

 

select substr(email,10) "도메인",
count(1) "고객수",
avg(age) "평균연령"
from customers
group by 1

 

[실습5] ‘[지역(시도)] 음식점이름 (음식종류)’ 컬럼을 만들고, 총 주문건수 구하기

table : from food_orders

[지역(시도)]  : '[', substring(addr, 1, 2), '] '

음식점 이름 : restaurant_name

(음식종류)  : ' (', cuisine_type, ')'

위 세개 합치기 : concat('[', substring(addr, 1, 2), '] ', restaurant_name, ' (', cuisine_type, ')')

총주문 건수 : count(1) "주문건수"컬럼별값구하기 : group by 1

select concat('[', substring(addr, 1, 2), '] ', restaurant_name, ' (', cuisine_type, ')') "바뀐이름",
       count(1) "주문건수"
from food_orders
group by 1

 

IF문과 CASE문

if(조건, 조건을 충족할 때, 조건을 충족하지 못할 때) : 엑셀과 비슷한 구조 

음식 타입을 ‘Korean’ 일 때는 ‘한식’, ‘Korean’ 이 아닌 경우에는 ‘기타’ 라고 지정하고 싶어요

select restaurant_name,
       cuisine_type "원래 음식 타입",
       if(cuisine_type='Korean', '한식', '기타') "음식 타입"
from food_orders

‘문곡리’ 가 평택에만 해당될 때, 평택 ‘문곡리’ 만 ‘문가리’ 로 수정

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

잘못된 이메일 주소 (gmail) 만 수정을 해서 사용

  전제조건 : 모든 gmail 도메인 데이터에는 @가 빠져있음

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

case when : 조건을 지정하다보면, 두 개 이상 지정을 해야 할 경우가 생깁니다.

else : 조건에 해당이 안되는 값을 분리하기위해 작성, 모든 값이 조건에 분리가 된다면 생략가능

case when 조건1 then 값(수식)1
     when 조건2 then 값(수식)2
     else 값(수식)3
end

else 미적용시 

select case when cuisine_type='korean' then '한식'
			when cuisine_type in ('japanese','chinese') then '아시아'
			 end "음식타입",
			cuisine_type
from food_orders

else 로 나머지값 미지정시 [NULL]로 표시

[실습1] 음식 타입을 ‘Korean’ 일 때는 ‘한식’, ‘Japanese’ 혹은 ‘Chienese’ 일 때는 ‘아시아’, 그 외에는 ‘기타’ 라고 지정

select case when cuisine_type='korean' then '한식'
			when cuisine_type in ('japanese','chinese') then '아시아'
			else '기타' end "음식타입",
			cuisine_type
from food_orders

[실습2] 음식 단가를 주문 수량이 1일 때는 음식 가격, 주문 수량이 2개 이상일 때는 음식가격/주문수량 으로 지정

table : from food_orders

컬럼 : 음식 가격 : price / 주문수량 : quantity

주문 수량이 1일 때는 음식 가격 : case when quantity=1 then price

주문 수량이 2개 이상일 때 음식가격/주문수량 : when quantity>=2 then price/quantity

select order_id,
       price,
       quantity,
       case when quantity=1 then price
            when quantity>=2 then price/quantity end "음식 단가"
from food_orders

+ if문으로 활용

SELECT order_id,
	price,
	quantity,
	if(quantity>=2, price/quantity,price) "음식단가"	
from food_orders

[실습3] 주소의 시도를 ‘경기도’ 일때는 ‘경기도’, ‘특별시’ 혹은 ‘광역시’ 일 때는 붙여서, 아닐 때는 앞의 두 글자만 사용

사용컬럼 :select restaurant_name,addr

table : from food_orders

‘경기도’ 일때는 ‘경기도’ : case when addr like '경기도%' then '경기도'

‘특별시’ 혹은 ‘광역시’ 일 때는 붙여서 : when addr like '%특별시' or addr like '%광역시%' then SUBSTR(addr,1,5)

아닐 때는 앞의 두 글자 : else SUBSTR(addr,1,2)

select restaurant_name,
	addr,
	case when addr like '경기도%' then '경기도' 
	when addr like '%특별시' or addr like '%광역시%' then SUBSTR(addr,1,5)
	else SUBSTR(addr,1,2)
	end '시도'
from food_orders

[실습4] 10세 이상, 30세 미만의 고객의 나이와 성별로 그룹 나누기 (이름도 같이 출력)

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 "그룹" 
from customers
where age between 10 and 29

[실습] 음식 단가, 음식 종류 별로 음식점 그룹 나누기

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 restaurant_name,
       order_id,
       delivery_time,
       price,
       addr,
       case when delivery_time>25 and delivery_time<=30 then price*0.05*(if(addr like '%서울%', 1.1, 1))
            when delivery_time>30 then price*1.1*(if(addr like '%서울%', 1.1, 1))
            else 0 end "수수료"
from food_orders

 

[실습]  배달시간이 늦었는지 판단하는 값을 만들기

조건 : 배달시간이 늦었는지 판단하는 값을 만들기

- 주중 : 25분 이상

- 주말 : 30분 이상

 

table : from food_orders

컬럼 : 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'

늦었을때 : late , 정상일때 : on-time

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 '지연여부'
from food_orders

'PM부트캠프' 카테고리의 다른 글

팀스파르타 PM과정 (06)  (1) 2026.03.16
팀스파르타 PM과정 (05)  (0) 2026.03.13
팀스파르타 PM과정 (03)  (1) 2026.03.11
팀스파르타 PM과정 (02)  (0) 2026.03.10
팀스파르타 PM과정 (01)  (0) 2026.03.09