본문 바로가기
SQL

[TIL] SQL_6일차(카테고리 만들기,수수료 구하기,cast( as ))

by 공부하죠 2024. 3. 29.
반응형

이전 시간에 이어서 SQL 데이터를 임의로 수정하는 방법에 대한 실습합니다.

✍🏻배운내용🌞

1. 이전 시간에 배운 내용을 응용한 실습(카테고리 만들기,수수료 구하기)

2. Data Type 오류 해결하기 cast( as )


📝[응용 실습] 

1. 새로운 카테고리 만들기 

조건문과 수식을 이용하여 간단한 '고객분류' 만들기  .

 

1-1. 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
where age between 10 and 29

 

1-2. 음식 단가, 음식 종류 별로 음식점 그룹 나누기

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 ('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

 

2. 조건문을 이용하여 다른 수식을 적용

조건문으로 서로 다른 식을 적용한 수수료 구하기

 

2-1. 지역배달시간을 기반으로 배달 수수료 구하기 (식당 이름, 주문 번호 함께 출력)

(지역 : 서울, 기타 - 서울일 때는 수수료 계산 * 1.1, 기타일 때는 곱하는 값 없음

시간 : 25분, 30분 - 25분 초과하면 음식 가격의 5%, 30분 초과하면 음식 가격의 10%)

select case when delivery_time>30 then price*0.1*if(addr like "%서울%", 1.1, 1)
           when delivery_time>25 then price*0.05*if(addr like "%서울%", 1.1, 1)
           else 0 end "수수료",
           restaurant_name, order_id, price, delivery_time, addr

from food_orders

 

2-2. 주문 시기음식 수를 기반으로 배달 할증료 구하기

(주문 시기 : 평일 기본료 = 3000 / 주말 기본료 = 3500

음식 수 : 3개 이하이면 할증 없음 / 3개 초과이면 기본료 * 1.2)

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)
           end "배달 할증료", restaurant_name, order_id, day_of_the_week, quantity
from food_orders

 

 

2. Data Type 오류 해결하기

1) 문자/숫자 계산을 했더니 오류가 났어요!

다른 SQL 문법에서는 data type 이 다를 때 연산이 되지 않을 수 있습니다.

출력 결과 컬럼명 옆의 ‘ABC’ 혹은 ‘123’ 을 확인해주세요. ‘ABC’ 는 문자로 저장이 되어있다는 의미입니다.)

 

🔔 문자, 숫자를 혼합하여 함수에 사용 할 때에는 데이터 타입을 변경해주어야 합니다!!

⚙ 숫자 decimal 로 변경
cast(if(rating='Not given', '1', rating) as decimal)

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

 

 

 

 


💡[ Tip ] SQL생각 흐름 🧠 

1. 기본구조를 적기 : select from where

2. 어떤 데이터를 가져올 테이블을 적기 : from 테이블

 → 만약 조건이 잘 파악이 안 되면 (전체) 테이블만 우선 실행하여 결과를 보고 조건 찾기

3. 어떤 컬럼을 이용할 것인지 선택 : select 컬럼

4. 어떤 조건을 지정할 지 적기 : where 조건, group by / order by

5. 어떤 함수(수식) 을 이용해야 하는가 → 갯수 구하는 수식

 

[ 복습 ]

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

substr(조회  컬럼, 시작 위치, 글자 )

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

if(조건, 조건을 충족할 때, 조건을 충족하지 못할 때)

case when 조건1 then 값(수식)1

         when 조건2 then 값(수식)2

         else 값(수식)3

         end


ADsP 시험 정보가 궁금하신 분들은 여기를 클릭 💨

이전 내용이 궁금하다면 여기를 클릭 💨

🌈 오늘 하루도 열공한 모두 즐거운 하루 되세요🌆

반응형