- 방법1 : 컬럼1 as 별명1
- 방법2 : 컬럼2 별명2| 구분 | 영문, 언더바 | 특수문자, 한글 |
|---|---|---|
| 방법 | 별명만 적음 | “별명” 으로, 큰 따옴표 안에 적어줌 |
| 예시 | ord_no | “ord no” / "주문번호" |
주문 (food_orders) 테이블에서 order_id, price, quantity 를 가져와서 ord_no, 가격, 수량 으로 별명 지어주기
select order_id ord_no, price "가격", quantity as "수량"
from food_orders fo ;
고객 (customers) 테이블에서 name, email 을 가져와서 이름, e-mail 으로 별명 지어주기
select name "이름", email as "e-mail"
from customers c ;
주문 (food_orders) 테이블에서 주문 금액이 20,000~30,000원 사이인 고객 조회하기
select *
from food_orders fo
where price BETWEEN 20000 and 30000;
주문 (food_orders) 테이블에서 B 로 시작하는 상점의 주문 조회하기
select *
from food_orders fo
where restaurant_name like 'B%';
주문 (food_orders) 테이블에서 한국음식이면서, 가격이 30,000원 이상인 경우 조회
select *
from food_orders fo
where fo.cuisine_type = 'Korean' and price >= 30000;
결제 (payments) 테이블에서 카드로 결제했거나, vat 율이 0.2 이하인 경우 조회
select *
from payments p
where pay_type = 'Card' or vat <= 0.2;
💁♀️ 상품 준비시간이 20~30분 사이인, 한국음식점의 식당명과 고객번호 조회하기
<select restaurant_name name, customer_id as customer
from food_orders fo
where food_preparation_time BETWEEN 20 and 30
and cuisine_type = 'Korean';
select count(1) count_of_orders,
count(distinct customer_id) count_of_customers
from food_orders주문 금액이 30,000원 이상인 주문건의 갯수 구하기
select COUNT(*)
from food_orders fo
where price >= 30000;
한국 음식의 주문 당 평균 음식가격 구하기
SELECT AVG(price)
from food_orders fo
where cuisine_type = 'Korean';
음식점별 주문 금액 최댓값 조회하기
select restaurant_name, MAX(price)
from food_orders fo
group by restaurant_name;
결제 타입별 가장 최근 결제일 조회하기
select pay_type, MAX(date)
from payments p
group by pay_type ;
음식점별 주문 금액 최댓값 조회하기 - 최댓값 기준으로 내림차순 정렬
select restaurant_name, max(price)
from food_orders fo
group by restaurant_name
order by MAX(price) desc;
고객을 이름 순으로 오름차순으로 정렬하기
select *
from customers c
order by name asc;
완성된 SQL 문의 기본 구조
select
from
where
group by
order by
HW. 2주차 숙제 해설
💁♀️ 음식 종류별 가장 높은 주문 금액과 가장 낮은 주문금액을 조회하고, 가장 낮은 주문금액 순으로 (내림차순) 정렬하기
<select cuisine_type, MAX(price), MIN(price)
from food_orders fo
group by cuisine_type
order by MIN(price) desc;
select count(1) count_of_orders,
count(distinct customer_id) count_of_customers
from food_ordersreplace(바꿀 컬럼, 현재 값, 바꿀 값) select restaurant_name "원래 상점명",
replace(restaurant_name, 'Blue', 'Pink') "바뀐 상점명"
from food_orders
where restaurant_name like '%Blue Ribbon%' select addr "원래 주소",
replace(addr, '문곡리', '문가리') "바뀐 주소"
from food_orders
where addr like '%문곡리%'
3) 원하는 문자만 남기기 (실습 포함)
substr(조회 할 컬럼, 시작 위치, 글자 수) select addr "원래 주소",
substr(addr, 1, 2) "시도"
from food_orders
where addr like '%서울특별시%'
4) 여러 컬럼의 문자를 합치기 (실습 포함)
SQL 에서는 여러 컬럼의 값을 하나로 합칠 수 있는 기능을 제공합니다.
예시) 서울시에 있는 음식점은 ‘[서울] 음식점명’ 이라고 수정하고 싶어요
함수명 : concat
사용 방법
붙일 수 있는 문자의 종류
[실습]
(서울시에 있는 음식점은 ‘[서울] 음식점명’ 이라고 수정)
select restaurant_name "원래 이름",
addr "원래 주소",
concat('[', substring(addr, 1, 2), '] ', restaurant_name) "바뀐 이름"
from food_orders
where addr like '%서울%'