6일차_엑셀보다 쉽고 빠른 SQL 4-1 ~ 4-4 Subquery

김채윤·2025년 9월 29일

오늘은,,~ 여러 연산을 한 번에 하고 싶을 때 사용하는 subquery를 배워보았다.
연산을 여러 번 거쳐야할 때 코드가 복잡해지므로 수학식에서 (a+b)*2같이 괄호를 사용해 먼저 덧셈을 먼저 연산하고 곱셈을 연산하는 것처럼 SQL에서도 subquery를 사용해서 할 수 있다.

Subquery에서 가장 주의할 점은 서브쿼리 안에 포함된 컬럼만 메인쿼리에서 사용할 수 있다는 것, 메인쿼리 from에 (서브쿼리)를 입력한다는 점

음식 준비 시간이 25분을 넘을 경우 몇분이 더 추가되는지를 구하고자 한다.

select order_id, restaurant_name, if(over_time>0, over_time, 0) over_time

#If 조건문을 사용해서 over time이 0보다 클 경우 over time을, 아닐 경우 0을 출력한다.

from 
(
select order_id, restaurant_name, food_preparation_time-25 over_time
from food_orders
) a

괄호 안에 subquery를 작성하고 이름을 지어준다. 'a'
음식 준비 시간-25분을 over time이라고 지어줬다.

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,
            #음식 단가에 따라 수수료를 계산해서 ratio_of_add라고 명명한다.
       price_per_plate
       #Price_per_plate*ratio_of_add를 출력하고 수수료라고 부른다.
from 
(
select restaurant_name, avg(price/quantity) price_per_plate
#음식 단가를 계산해서 price_per_plate라고 명명한다.
from food_orders
group by 1
) a
) b
#b안에 a가 있는, 서브쿼리 안의 서브쿼리 구조

음식점 타입별 음식점 수와 수량에 따라 수수료를 출력하기

오류가 발생했다..
1. 서브쿼리의 select에 있는 컬럼만 메인쿼리에서 출력 가능하다. 서브쿼리 안에 price가 없기 때문에 메인쿼리에 입력하면 오류가 남.
2. case when then 뒤에 반점을 붙여서

SELECT cuisine_type,
       total_quantity,
       count_res,
       case when count_res>=5 and total_quantity>=30 then 0.005
            when count_res>=5 and total_quantity<30 then 0.008
            when count_res<5 and total_quantity>=30 then 0.01
            when count_res<5 and total_quantity<30 then 0.02
            end rate             
from 
(
select cuisine_type,
       sum(quantity) total_quantity,
       count(distinct restaurant_name) count_res
from food_orders
group by 1
) a

오류를 없애고 출력완,,!
팁은 서브쿼리로 어떤 걸 먼저 할지 적고 메인쿼리를 작성한다.

음식점의 총 주문수량과 주문 금액을 연산하고 주문 수량을 기반으로 수수료를 구하고자 한다.
수량 5개 이하는 10%
수량 15개 초과, 총 주문금액 300000원 이상은 0.5%
그 외 일괄 1%

에러 발생,,,
메인쿼리 부분에 from을 안 적어서 생긴 오류이다.

select restaurant_name,
       total_orders,
       total_price,
       case when total_orders<=5 then 0.1
            when total_orders>15 and total_price>=300000 then 0.005
            else 0.01 end rate
from
(
SELECT restaurant_name,
       sum(quantity) total_orders,
       sum(price) total_price
from food_orders
group by restaurant_name
) a

From을 적었더니 제대로 출력완,,!

아직은 서브쿼리를 쓰는 게 더 복잡하게 느껴지지만 많이 연습해서 적응하면 길게 코드를 늘여놓는 것보다 더 간단한 식을 완성할 수 있을 것 같다!

0개의 댓글