SQL

기본 연산, 최대/최소, 개수 구하기

content0474 2024. 8. 27. 15:43

 select 다음에 써주면 된다

기본 연산

select a, b, a+b as c 

-> c컬럼이 새로 만들어지고 a+b를 한 값이 써진다

 

select food_preparation_time,
       delivery_time,
       food_preparation_time + delivery_time as total_time
from food_orders

 

select sum(컬럼): 컬럼의 총 합

select avg(컬럼): 컬럼의 평균

 

최대/최소

select min(컬럼)  지정한 컬럼의 최솟값

select max(컬럼)  지정한 컬럼의 최댓값

 

select min(price) min_price,
       max(price) max_price
from food_orders

 

개수 구하기

count: 데이터의 개수

count(컬럼): 컬럼의 데이터(행) 개수

count(1) 또는 count(*): 테이블 내 전체 데이터(행) 개수

distinct: 값의 개수

count(distinct 컬럼): 컬럼 내 값의 개수 

나이가 21, 22, 21, 25, 25, 27이면

count는 6, distinct는 4

 

select count(1) count_of_orders,
       count(distinct customer_id) count_of_customers
from food_orders

: food_orders테이블에 있는 데이터 전체 개수를 새서 count_of_orders로 표기하고(=주문 건수), customer_id에 몇 개의 값이 있는지 새서 count_of_customers로 표기(=주문 고객 수)

 

where절을 이용한 데이터 뽑기

남자 나이의 평균 구하기

select avg(age) "남자 나이 평균"
from customers

where gender='male'

 

15000원 이상인 이탈리아 음식 주문건수 구하기

select count(order_id)

from food_orders

where price>=15000

and cuisine_type='Italian'