Chapter 2. SQL을 이용해서 계산하기

select food_preparation_time,
delivery_time,
food_preparation_time + delivery_time as total_time
#+를 사용하여 음식 준비 시간과 배달 시간을 합친 시간을 계산하고 as로 컬럼을 명명한다.
from food_orders

select sum(food_preparation_time) total_food_preparation_time,
avg(delivery_time) avg_food_delivery_time
#sum과 avg를 사용하여 합계와 평균값을 출력. 뒤에 해당 값들을 어떤 컬럼으로 명명할지 작성
from food_orders

select count(1) count_of_orders, #count(1) 또는 count(*)을 입력하면 테이블 안의 모든 데이터 개수를 출력
count(distinct customer_id) count_of_customers #distinct를 입력하면 중복 없이 데이터 개수를 출력
from food_orders
주문 수는 1898이지만 주문을 한 고객 수는 중복을 빼고 1200명임
*실습문제

select count(1) as total_count
from payments
결제 건은 1716건이 있는 것을 확인할 수 있다.

select count(distinct pay_type) as count_of_pay_type
from payments
distinct를 사용해서 두 가지의 결제 타입이 있는 걸 확인할 수 있다.

select min(price) min_price,
max(price) max_price
from food_orders
min과 max를 이용해서 최대값 최소값을 구할 수 있다.

select count(1) as count_of_price_morethan_30000
from food_orders
where price>=30000
#결제 금액이 30000원 이상인 결제 건수를 출력

select avg(price) as avg_price
from food_orders
where cuisine_type='Korean'
한국 음식의 평균가를 출력할 수 있다.

select cuisine_type,
sum(price) sum_of_price
from food_orders
group by cuisine_type
#음식 종류별로 합산 금액을 출력
범주별로 나누어서 계산하고 싶다면 group by절을 사용한다.

select restaurant_name, max(price) as max_price
from food_orders
group by restaurant_name
#음식점별로 묶어서 최고가를 출력

select pay_type, max(date) as latest_paytype_date
from payments
group by pay_type
#결제 방법별로 묶어서 가장 최근 날짜를 출력