데이터 분석(SQL) 1일차 - mysql 사용
select 컬럼1, 컬럼2
from 테이블
select *
from food_orders
select에 *를 넣으면 food_orders 테이블에 있는 모든 컬럼을 보여줘
컬럼 선택할 경우 select에 원하는 컬럼명 입력
방법1: 컬럼1 as 별명1
방법2: 컬럼2 별명2
select restaurant_name as '음식점', addr address
from food_orders
select name as '이름', email 'e-mail'
from customers
customers 테이블에 있는 name과 email 컬럼 이름 변경
select *
from 데이블
where 필터링 조건
select *
from customers
where age = 21
customer 테이블에서 age가 21인 경우만 보여줘
<비교연산자의 종류 >
| 비교연산자 | 의미 | 예시 |
|---|---|---|
| = | 같다 | age = 21gender = 'female' |
| <> | 같지 않다 (다르다) | age <> 21gender <> 'female' |
| > | 크다 | age > 21 |
| >= | 크거나 같다 | age >= 21 |
| < | 작다 | age < 21 |
| <= | 작거나 같다 | age <= 21 |
-기본 문법: between A and b
where age between 10 and 20
나이가 10과 20사이일 경우 출력
-기본 문법: in (A,B,C)
where age in (15, 21, 31)
나이가 15,21,31세인 경우
where cuisine_type in ('Korean', 'Japanese')
음식 종류가 한식, 일식인 경우
where name like '김%' <-'김'으로 시작하는 이름
where restaurant_name like "%Next%' <- 식당 이름에 'Next'를 포함하는 경우
where name like '%임' <- '임'으로 끝나는 이름
select*
from food_orders
where cuisine_type = 'Korean'
and price >= 30000
| 논리연산자 | 의미 | 예시 |
|---|---|---|
| AND | 그리고 | age > 20 and gender = 'female'→ 나이가 20세 이상이고, 여성 |
| OR | 또는 | age > 20 or gender = 'female'→ 나이가 20세 이상이거나, 여성 |
| NOT | 아닌 | not gender = 'female'→ 여성이 아닌 |
select food_preparation_time,
delivery_time,
food_preparation_time + delivery_time as total_time
from food_orders
food_preparation_time + delivery_time 합으로 새 컬럼 만들수 있다.
-합계: sum(컬럼)
-평균: avg(컬럼)
select sum(food_preparation_time) total_food_preparation_time,
avg(delivery_time) avg_food_preparation_time
from food_orders
음식 준비시간의 합계와 평균 구하기
갯수: count(컬럼)
컬럼명을 지정하지 않을 때는 1 혹은 * 사용가능
컬럼명 지정할때는 distinct 사용하기
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 카테고리컬럼(원하는컬럼 아무거나),
sum(계산 컬럼),
from 테이블
group by 카테고리컬럼(원하는컬럼 아무거나)
select cuisine_type,
sum(price) sum_of_price
from food_orders
group by cuisine_type
음식 종류별 주문 금액 합계
| 종류 | 구문 | 예시 |
|---|---|---|
| 오름차순 | 생략 | ORDER BY SUM(price) |
| 내림차순 | DESC | ORDER BY SUM(price) DESC |
select 카테고리컬럼(원하는컬럼 아무거나),
sum(계산 컬럼),
from 테이블
group by 카테고리컬럼(원하는컬럼 아무거나)
order by 정렬을 원하는 컬럼 (카테고리컬럼(원하는컬럼 아무거나), sum(계산 컬럼) 둘 다 가능)
select cuisine_type,
sum(price) sum_of_price
from food_orders
group by cuisine_type
order by sum(price) desc
select cuisine_type,
max(price) max_price,
min(price) min_price
from food_orders
group by cuisine_type
order by min_price desc
1) Is not null
where name is not null
2) Having
SELECT NAME, COUNT() AS count
FROM ANIMAL_INS
WHERE NAME IS NOT NULL
GROUP BY NAME
HAVING COUNT() >= 2
각 동물 이름별로 몇 마리 있는지 계산하고, 2마리 이상 있는 이름만 조회(having 사용)
3) limit
SELECT NAME, DATETIME
FROM ANIMAL_INS
ORDER BY DATETIME ASC
LIMIT 3 <- 가장 먼저 들어온 동물 3마리만 조회.