본문 바로가기
내일배움캠프 AI 웹 프로그래밍

내일배움캠프 72일차_SQL 실습: User Segmentation & Subquery

by thriveview 2023. 11. 6.

학습목표:

조건문과 Subquery 를 결합하여 user segmentation 과 연산을 해봅시다

하나의 쿼리문에서 수행하기 어려운 복잡한 연산을 Subquery 로 실행해봅시다

 

실습:

- 음식점의 평균 단가별 segmentation 을 진행하고, 그룹에 따라 수수료 연산하기
(수수료 구간 - 
     ~5000원 미만 0.05%
    ~20000원 미만 1%
    ~30000원 미만 2%
    30000원 초과 3%)

select restaurant_name,
       price_per_plate*ratio_of_add "수수료"
from 
(
select restaurant_name,
       case when price_per_plate<5000 then 0.005
            when price_per_plate between 5000 and 19999 then 0.01
            when price_per_plate between 20000 and 29999 then 0.02
            else 0.03 end ratio_of_add,
       price_per_plate
from 
(
select restaurant_name, avg(price/quantity) price_per_plate
from food_orders
group by 1
) a
) b

 

 

실습2. 음식점의 총 주문수량과 주문 금액을 연산하고, 주문 수량을 기반으로 수수료 할인율 구하기

(할인조건 수량이 5개 이하 → 10% 수량이 15개 초과, 총 주문금액이 300000 이상 → 0.5% 이 외에는 일괄 1%)

select restaurant_name,
       case when sum_of_quantity<=5 then 0.1
            when sum_of_quantity>15 and sum_of_price>=300000 then 0.005
            else 0.01 end ratio_of_add
from 
(
select restaurant_name,
       sum(quantity) sum_of_quantity,
       sum(price) sum_of_price
from food_orders
group by 1
) a

 

 

마지막으로 정리하며, 서브쿼리의 특징을 살펴보자 

 

1. 서브쿼리는 쿼리를 구조화시키므로, 쿼리의 각 부분을 명확히 구분할 수 있게 해줌

2. 서브쿼리는 복잡한 JOIN이나 UNION과 같은 동작을 수행할 수 있는 또 다른 방법을 제공함

3. 서브쿼리는 복잡한 JOIN이나 UNION 보다 좀 더 읽기 편한편.

 

주의할 사항으로는 서브쿼리는 반드시 괄호로 묶어야 한다. 

또한 실행결과가 단일,다중행인지에 따라 적절한 연산자를 사용할 줄 알아야 하며 행 구분도 할 줄 알아야 한다.