데이터 분석 - SQL

hyun-jin·2025년 2월 17일

데이터 분석

목록 보기
1/100
post-thumbnail

데이터 분석(SQL) 1일차 - mysql 사용

1. SQL 데이터 조회

1) SQl의 가장 기본구조인 SELECT 와 FROM

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 컬럼 이름 변경

  • as를 사용해서 변경 또는 사용 하지 않고 바로 변경 이름 작성 가능
  • 한국명이거나 특수문자(- 등)가 들어 가는 경우 '' 안에 작성해야함. 영문일 경우 '' 생략 가능

2) where 절 -> 조건에 맞는 데이터롤 필터링하기

select *
from 데이블
where 필터링 조건

select *
from customers
where age = 21

customer 테이블에서 age가 21인 경우만 보여줘

<비교연산자의 종류 >

비교연산자의미예시
=같다age = 21
gender = 'female'
<>같지 않다 (다르다)age <> 21
gender <> 'female'
>크다age > 21
>=크거나 같다age >= 21
<작다age < 21
<=작거나 같다age <= 21

2. 조건의 종류 - between, in, like

1) between: A 와 B사이

-기본 문법: between A and b

where age between 10 and 20

나이가 10과 20사이일 경우 출력

2) in: '포함' 하는 조건

-기본 문법: in (A,B,C)

where age in (15, 21, 31)

나이가 15,21,31세인 경우

where cuisine_type in ('Korean', 'Japanese')

음식 종류가 한식, 일식인 경우

3) like: 완전히 똑같지는 않지만, 비슷한 값을 조건으로 주기

  • 기본 문법: like '시작문자%'
                  like '%시작문자%'
                  like '%시작문자'

    where name like '김%' <-'김'으로 시작하는 이름
    where restaurant_name like "%Next%' <- 식당 이름에 'Next'를 포함하는 경우
    where name like '%임' <- '임'으로 끝나는 이름

3. 논리연산 - 여러 개의 조건으로 필터링하기 (and, or, not)

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'
→ 여성이 아닌

4. 계산식 (sum, avg, count, min, max)

1) 숫자 연산 사용 (+, -, *, /)

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

food_preparation_time + delivery_time 합으로 새 컬럼 만들수 있다.

2) 기본 연산 (sum, avg)

-합계: sum(컬럼)
-평균: avg(컬럼)

select sum(food_preparation_time)    total_food_preparation_time,
        avg(delivery_time)    avg_food_preparation_time
from food_orders

음식 준비시간의 합계와 평균 구하기

3) 데이터 갯수 (count)

  • 갯수: count(컬럼)
    컬럼명을 지정하지 않을 때는 1 혹은 * 사용가능
    컬럼명 지정할때는 distinct 사용하기

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

    주문건수와, 주문 한 고객 수 구하기

4) 데이터 범위 (min, max)

  • 최소값: min(컬럼)
  • 최댓값: max(컬럼)

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

음식의 최소 가격, 최대 가격 구하기

5. 범주별 연산 (group by)

  • 카테고리를 지정하여 수식 함수로 현산을 할 수 있다.
  • group by는 카테고리 컬럼 지정, 그리고 group by를 적어주는 것으로 적용 가능

1) 기본구조

select 카테고리컬럼(원하는컬럼 아무거나),
         sum(계산 컬럼),
from 테이블
group by 카테고리컬럼(원하는컬럼 아무거나)

select cuisine_type,
         sum(price) sum_of_price
from food_orders
group by cuisine_type

음식 종류별 주문 금액 합계

6. 정렬하기 (order by)

  • 오름차순: 숫자가 점점 커지는 순서로 정렬(기본값)
  • 내림차순: 숫자가 점점 작아지는 순서로 정렬
종류구문예시
오름차순생략ORDER BY SUM(price)
내림차순DESCORDER BY SUM(price) DESC

1) 기본구조

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

7. 문제 풀이중 배운것

1) Is not null

  • 데이터에서 NULL이 아닌 값만 조회하려면 IS NOT NULL 조건을 사용

    where name is not null

2) Having

  • HAVING은 GROUP BY로 그룹화한 결과에서 조건을 적용할 때 사용됨.

    SELECT NAME, COUNT() AS count
    FROM ANIMAL_INS
    WHERE NAME IS NOT NULL
    GROUP BY NAME
    HAVING COUNT(
    ) >= 2

각 동물 이름별로 몇 마리 있는지 계산하고, 2마리 이상 있는 이름만 조회(having 사용)

3) limit

  • LIMIT은 SQL에서 조회 결과의 출력 개수를 제한할 때 사용됨.
  • LIMIT 개수 만큼만 결과를 출력.

    SELECT NAME, DATETIME
    FROM ANIMAL_INS
    ORDER BY DATETIME ASC
    LIMIT 3 <- 가장 먼저 들어온 동물 3마리만 조회.

0개의 댓글