SELECT food_preparation_time, delivery_time, food_preparation_time + delivery_time AS total_time FROM food_orders
연산자 | 설명 |
---|---|
+ | 더하기 |
- | 빼기 |
* | 곱하기 |
/ | 나누기 |
SELECT SUM(food_preparation_time) total_food_preparation_time, AVG(delivery_time) avg_delivery_time FROM food_orders
💡 전체 주문 건수는 10건, 주문한 사람은 5명일 경우 COUNT(1) → 10, COUNT(DISTINCT 고객명) → 5
SELECT COUNT(1) count_of_orders, COUNT(DISTINCT customer_id) count_of_customers FROM food_orders
SELECT MIN(price) min_price, MAX(price) max_price FROM food_orders
SELECT COUNT(1) AS cnt_orders FROM food_orders WHERE price >= 30000
(1) 흐름 파악
ㄱ. 어떤 테이블에서 데이터를 뽑을 것인가 → 주문 테이블
ㄴ. 어떤 컬럼을 이용할 것인가 → 주문 금액, 주문 번호
ㄷ. 어떤 조건을 지정해야 하는가 → 30,000원 이상
ㄹ. 어떤 함수 (수식) 을 이용해야 하는가 → 갯수 구하는 수식
(2) 구문 만들기
ㄱ. 어떤 테이블에서 데이터를 뽑을 것인가 → from food_orders
ㄴ. 어떤 컬럼을 이용할 것인가 → order_id, price
ㄷ. 어떤 조건을 지정해야 하는가 → where price >= 30000
ㄹ. 어떤 함수 (수식) 을 이용해야 하는가 → count(order_id) 혹은 count(1)
(3) 최종
SELECT COUNT(order_id) count_of_orders
FROM food_orders
WHERE price>=30000
SELECT AVG(price) AS average_price FROM food_orders WHERE cuisine_type = 'Korean'
SELECT column_name(s) FROM table_name WHERE condition GROUP BY column_name(s);
select cuisine_type, sum(price) sum_of_price from food_orders group by cuisine_type
SELECT restaurant_name, MAX**(price) AS max_price FROM food_orders GROUP BY restaurant_name
SELECT pay_type, MAX(date) AS recent_date FROM payments GROUP BY pay_type
💡가장 최근 결제일도 MAX 함수! (날짜 중 가장 큼 = 가장 최근)
SELECT column_name(s), SUM(column) FROM table_name WHERE condition GROUP BY column_name(s) ORDER BY column_name(s);
ORDER BY column1, column2, ...
종류 | 구문 | 예시 |
---|---|---|
오름차순 | 생략 | ORDER BY SUM(price) |
내림차순 | DESC | ORDER BY SUM(price) DESC |
SELECT cuisine_type, SUM(price) AS sum_of_price FROM food_orders GROUP BY cuisine_type ORDER BY SUM(price)
SELECT restaurant_name,
MAX(price) AS max_price
FROM food_orders
GROUP BY restaurant_name
ORDER BY MAX(price) DESC
SELECT *
FROM customers
ORDER BY name
select
from
where
group by
order by
→ (5)-(4)-(3)-(2)-(1)
→ (2)-(5)-(1)-(4)-(3)
SELECT cuisine_type,
MIN(price) min_price,
MAX(price) max_price
FROM food_orders
GROUP BY cuisine_type
ORDER BY MIN(price) DESC