1. 계산하기 다 select에 씀
1-1. 숫자연산 + - * /
select food_preparation_time, # 여러 컬럼 추출 시 ,(쉼표) 추가
delivery_time,
food_preparation_time + delivery_time as total_time # 컬럼1 + 컬럼2 as 명명
from food_orders
1-2. SUM( ), AVG( )
select sum(food_preparation_time) total_food_preparation_time, # sum(괄호) # 영문+언더바 조합이라 as나 ''없음
avg(delivery_time) avg_food_delivery_time # avg(괄호) # 영문+언더바 조합이라 as나 ''없음
from food_orders
1-3. COUNT( )
count(1) = count(*) 테이블 안에 전체 데이터의 개수는 몇 개?
count(distinct 컬럼명) 특정 컬럼의 데이터의 개수는 몇 개?
select count(1) count_of_orders, # food_orders 테이블 안에 있는 모든 데이터의 개수
count(distinct customer_id) count_of_customers # customer_id 컬럼 안에 있는 데이터의 개수
from food_orders
1-4. MIN( ), MAX( )
select min(price) min_price, # 쉼표 추가
max(price) max_price
from food_orders
1-5. 실습
[실습1] 주문 금액이 30,000원 이상인 주문건의 갯수 구하기
SELECT 어떤 테이블 ? ▶ FROM 어떤 컬럼 ? ▶ WHERE 어떤 조건 ? ▶ COUNT 어떤 함수?
select count(1) count_orders # count()는 select에서 나옴!
from food_orders
where price >= 30000 # where 조건을 충족하는 모든 데이터 개수 카운트해줘 = count(1)
# count_orders라고 불러줘
[실습2] 한국 음식의 주문 당 평균 음식 가격 구하기
SELECT 어떤 테이블 ? ▶ FROM 어떤 컬럼 ? ▶ WHERE 어떤 조건 ? ▶ AVG 어떤 함수?
select avg(price) as average_price
from food_orders
where cuisine_type='Korean'
2. GROUP by where 아래에 씀
그룹화 기능 순서: select > from > (where) > group by
[실습] 결제 타입별 가장 최근 결제일 조회
최근 결제일 max(date)
select pay_type,
max(date) recent_date # 최근일은 max(date)
from payments
group by pay_type # 결제 타입별
3. ORDER by group by 아래에 씀
정렬 기능 순서: select > from > (where) > (group by) > order by
order by sum(price) 합계 기준 정렬(오름차순)
order by sum(price) desc 합계 기준 정렬(내림차순)
select cuisine_type,
sum(price) sum_of_price # 주문 금액의 합계
from food_orders
group by cuisine_type # 음식 타입별로
order by sum(price) # 합계 기준으로 정렬(오름차순)
order by sum(price) desc # 합계 기준으로 정렬(내림차순)
[실습] 고객을 이름 순, 성별별로 오름차순 정렬하기
select * # 특정 컬럼 추출을 원한 것이 아니므로 *
from customers
order by gender, name # 쉼표로 넣어주면 됨 # 오름차순은 desc 필요 없음
[숙제] 음식 종류별 가장 높은 주문 금액과 가장 낮은 주문금액을 조회하고, 가장 낮은 주문금액 순으로 (내림차순) 정렬하기
순서 select > from > (where) > group by > order by
select min( ), max( )는 select에 씀
결과의 그래프를 보고 select에 어떤 항목 불러올건지 참고
group by 질문의 "~별" 주목
order by select에서 명명한 별명(min_price)가 나옴
desc 내림차순
select cuisine_type,
min(price) min_price, # min(), max()는 select에 씀
max(price) max_price
from food_orders
group by cuisine_type # 음식 종류별
order by min_price desc # 가장 낮은 주문 금액(위에서 min_price로 명명) 순 내림차순(desc)
'SQL > SQL 학습' 카테고리의 다른 글
SQL 4주차①(subquery) (0) | 2025.04.28 |
---|---|
SQL 3주차②(case when then) (0) | 2025.04.25 |
SQL 3주차②(if문) (1) | 2025.04.25 |
SQL 3주차①(replace, substr, concat) (0) | 2025.04.24 |
SQL 1주차(컬럼, 필터링, 논리 연산) (0) | 2025.04.23 |