스파르타 코딩클럽/[강의] 엑셀보다 쉽고 빠른 SQL
[엑셀보다 쉽고 빠른 SQL] 4주차. Subquery와 Join
sance
2023. 12. 26. 15:36
효율적인 쿼리문 Subquery
- Query 안에 sub로 들어간 구문(쿼리문 안에 포함된 또 다른 쿼리문)
- 주로 WHERE절, FROM절, HAVING절 등에 사용
- 기본 구조
select column1, special_column
from
(select column1, column2 special_column
from table1) a
select column1, column2
from table1
where column1 = (select col1 from table2)
여러 테이블에서 데이터 불러오기 Join
- 공통 컬럼을 기준으로 서로 다른 테이블을 합쳐서 필요한 데이터 조회
- LEFT JOIN : 공통 컬럼을 기준으로 하나의 테이블에 값이 없어도 모두 조회
- INNER JOIN : 공통 컬럼을 기준으로 두 테이블 모두에 있는 값만 조회
- 기본 구조
-- LEFT JOIN
select a.column1, b.column1
from table1 a left join table2 b on a.column=b.column
-- INNER JOIN
select a.column1, b.column1
from table1 a inner join table2 b on a.column=b.column
4주차 과제
식당별 평균 음식 주문 금액과 주문자의 평균 연령을 기반으로 Segmentation 하기
- 평균 음식 주문 금액 기준 : 5,000 / 10,000 / 30,000 / 30,000 초과
- 평균 연령 : ~ 20대 / 30대 / 40대 / 50대 이상
* 두 테이블 모두에 데이터가 있는 경우만 조회, 식당 이름 순으로 오름차순 정렬
평균 주문 금액과 주문자 평균 연령을 식당별로 그룹화하는 서브쿼리문을 만들고
계산된 평균금액과 평균연령을 조건문으로 필터링해준다. 기준이 여러개이기때문에 CASE를 사용했다.
select restaurant_name,
case when price<=5000 then 'price_group1'
when price>5000 and price<=10000 then 'price_group2'
when price>10000 and price<=30000 then 'price_group3'
when price>30000 then 'price_group4' end price_group,
case when age<30 then 'age_group1'
when age<40 then 'age_group2'
when age<50 then 'age_group3'
else 'age_group4' end age_group
from
(select f.restaurant_name, avg(f.price) price, avg(c.age) age
from food_orders f inner join customers c on f.customer_id=c.customer_id
group by 1) a
order by 1
▼ 결과
