[TIL] SQL 3주차

최하온·2023년 12월 27일
0

TIL

목록 보기
6/71
post-thumbnail

What I learned new

SQL 3주차


replace

: 지정문자를 다른 문자로 수정
replace(바꿀 컬럼, '현재 값', '바꿀 값')

select restaurant_name "원래 상점명",
       replace(restaurant_name, 'Blue', 'Pink') "바뀐 상점명" 		 -- restaurant_name 컬럼에서 Blue=> Pink
from food_orders
where restaurant_name like '%Blue Ribbon%'

substr

: 원하는 특정 문자만 추출
substr(조회 할 컬럼, 시작 위치, 글자 수)

select addr "원래 주소",
       substr(addr, 1, 2) "시도" 		-- addr column에서 1번째 부터 두 글자를 추출
from food_orders
where addr like '%서울특별시%'

concat

: 여러 컬럼의 문자를 합쳐 원하는 포맷팅
concat(붙이고 싶은 값1, 붙이고 싶은 값2, ...)

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

조건문

if문

if(조건, 조건을 충족 할 때, 충족하지 못할 때) : 어떤 조건이 주어질 때 어떤 동작을 수행하도록 하는 문

select restaurant_name,
       cuisine_type "원래 음식 타입",
       if(cuisine_type='Korean', '한식', '기타') "음식 타입"			--cuisine_type='Korean'라는 조건에 부합하면 한식, 그렇지 않으면 기타 반환
from food_orders
select addr "원래 주소",
       if(addr like '%평택군%', replace(addr, '문곡리', '문가리'), addr) "바뀐 주소"		--addr에 평택군이라는 문자열이 있다면 replace하고 아니면 addr 반환
from food_orders
where addr like '%문곡리%'		--문곡리로 한 번 필터링
select substring(if(email like '%gmail%', replace(email, 'gmail', '@gmail'), email), 10) "이메일 도메인",
       count(customer_id) "고객 수",		--여러가지 기능을 병합하여 사용 가능.
       avg(age) "평균 연령"
from customers
group by 1		-- avg를 구했으니 그룹화 해주기

case 문

조건이 여러가지 일 때!
when : 조건을 쓸 때
else : 앞에 조건이 다 부합하지 않으면 (생략가능)
then : ~라고 해줘
end : case문 끝낼 때

case when 조건1 then 값(수식)1
     when 조건2 then 값(수식)2
     else 값(수식)3
end
select order_id,
       price,
       quantity,
       case when quantity=1 then price 		--quantity=1 일 때 price 반환
            when quantity>=2 then price/quantity end "음식 단가" 		-- quantity>=2 일 때 price/quantity 반환
from food_orders
select restaurant_name,
       addr,
       case when addr like '%경기도%' then '경기도'		-- addr에 '경기도'가 있다면 '경기도'라고 해줘
            when addr like '%특별%' or addr like '%광역%' then substring(addr, 1, 5)		--addr에 '특별'이나 '광역'이 있다면 substring 실행
            else substring(addr, 1, 2) end "변경된 주소"			-- 다 아니라면 substring 실행
from food_orders

데이터 타입 오류

date type 오류 시 타입을 변경 해주어야 함.
숫자로 변경
cast(if(rating='Not given', '1', rating) as decimal)

문자로 변경
concat(restaurant_name, '-', cast(order_id as char))


Issue occuring


How solve issue


when 주말 and 배달 시간이 30분 이상 then 지연, 평일 and 배달 시간이 25분 이상 then 지연,
else 지연 아님. end 끝!

Realization


미리 어떤 테이블, 컬럼 등을 사용할지 적어놓으니 훨씬 수월했다.

오늘은 두 강의를 따라가느라 늦게 끝났다. 뭔가 공부하고 나면 마음이 편해진다.

어제 춘식이 목욕하느라 늦게 자서 그런가 몇 번 졸아서 인터넷에서 졸음 깨워주는 걸 샀다. 효과가 있으면 좋겠는걸.

0개의 댓글