카테고리 없음

엑셀보다 쉽고 빠른 SQL - 4주차

gamzaa914 2025. 4. 30. 17:30

수업 들은 당일에 못 써서 오늘 복습하면서 작성하고 있다.

5주차가 먼저 있고 4주차가 나중에 있는 이유이다..

 

 


4주차


 

1. 여러 번의 연산을 한 번의 SQL 문으로 수행하기(Subquery)

 

  - Subquery가 필요한 경우

  • 여러번의 연산을 수행해야 할 때
  • 조건문에 연산 결과를 사용해야 할 때
  • 조건에 Query 결과를 사용하고 싶을 때

 

 

  ex) 주문 테이블에서 주문 번호, 음식점명, 음식 준비시간을 가져오기

select order_id,
	   restaurant_name,
	   food_preparation_time
from
(
select order_id,
	   restaurant_name,
	   food_preparation_time
from food_orders
) a

 

 

 

  ex) 음식점의 지역과 평균 배달시간으로 segmentation 하기

select restaurant_name,
	   sido,
	   case when avg_time <= 20 then '<=20'
	        when avg_time > 20 and avg_time <= 30 then '20<x<=30'
	        when avg_time > 30 then '>30'
	   end time_segment
from
(
select restaurant_name,
	   substr(addr, 1, 2) sido,
	   avg(delivery_time) avg_time
from food_orders
group by 1, 2
) a

 

 

 

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

        (할인 조건: 수량이 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

 

 

2. 필요한 데이터가 서로 다른 테이블에 있을 때 조회하기(Join)

  • Left Join: 공통 컬럼을 기준으로, 하나의 테이블에 값이 없더라도 모두 조회되는 경우를 의미합니다.
  • Inner Join: 공통 컬럼을 기준으로, 두 테이블 모두에 있는 값으로 조회합니다.
select 조회 할 컬럼
from 테이블1 a left(inner) join 테이블2 b on a.공통컬럼명 = b.공통컬럼명   #기본 구조

 

 

  ex) 주문 가격과 수수료율을 곱하여 주문별 수수료 구하기(조회커럼: 주문 번호, 식당 이름, 주문 가격, 수수료율, 수수료)

         * 수수료율이 있는 경우만 조회

select f.order_id,
	   f.restaurant_name,
	   f.price,
	   p.vat,
	   f.price*p.vat "수수료율"
from food_orders f inner join payments p on f.order_id = p.order_id