[정리] 엑셀보다 쉽고 빠른 SQL - 1

ryuns·2025년 3월 27일

SQL

목록 보기
1/4

#수강 강의 : 엑셀보다 쉽고 빠른 SQL
1주차 ~ 3주차

# SQL 문법 위치
select 기준컬럼, 컬럼, 계산함수(), 출력값 수정, 조건문
from 테이블
where 조건
group by 기준컬럼
order by 컬럼 [desc]


📃 개념 정리

SQL : 데이터베이스와 대화를 하기 위한 언어
데이터베이스 : 쉽게 말해 ‘데이터가 저장되어있는 큰 폴더’
테이블 : 마치 ‘엑셀 파일’과 같이 생겼습니다.
열: ‘컬럼’ 혹은 ‘필드’
Query : DB에 명령을 내리는 것

  • ctrl+enter : 코드 실행

1. 조회

SELECT

select * from 테이블 #전체 검색
select 컬럼1, 컬럼2, ... from 테이블 #일부 검색

컬럼 별명 짓기

  • 영문 : ord_no
  • 특수문자,한글(큰따옴표 필요) : “ord no”
컬럼1 as 별명1
컬럼2 별명2

WHERE

  • 조건 중첩 : AND / OR / NOT
select 컬럼 from 테이블 where 조건1 and 조건2

조건문

  • 같다(기본 조건) : =
  • 다르다 : <>
  • A 와 B 사이: between a and b
select * from 테이블 where gender='female'
					where age between 10 and 20           
  • 포함 : in (A, B, C)
... where age in (15, 21, 31) #조건이 숫자
... where cuisine_type in ('Korean', 'Japanese') #문자
  • 비슷한 값 : like
... where name like '김%' # 김으로 시작
... where name like '%Next%' # Next가 포함된 것
... where name like '%임' # 임으로 끝

2. 계산

기본 연산 : + - * /
함수 : SUM(컬럼) AVG(컬럼) MIN(컬럼) MAX(컬럼)
갯수 : COUNT(컬럼)

select 숫자컬럼 + 숫자컬럼 from 테이블
select sum(컬럼), avg(컬럼) from 테이블

# count(1) = count(*) : 테이블의 모든 개수를 샘
select count(1) from 테이블
		count(컬럼) # 컬럼의 개수를 구함
		count(distinct 컬럼) # 컬럼내의 중복 제거한 수

GROUP BY : 타입별 계산

select 기준컬럼, 계산함수() from 테이블 group by 기준컬럼

select substr(addr,1,2) '지역', cuisine_type "타입", avg(price) "평균금액"
from food_orders
where addr like '%서울%'
group by 1, 2 #substr(addr,1,2) cuisine_type ✨

ORDER BY : 정렬

내림차순 : desc

select restaurant_name, max(price)
from food_orders
group by restaurant_name
order by price desc

3. 출력값 수정

DB 반영 X

replace : 값 변경

replace(컬럼, 현재 값, 바꿀 값)# restaurant_name에서 Blue라고 적힌 부분을 Pink로 바꿔줘
select restaurant_name "원래 상점명",
       replace(restaurant_name, 'Blue', 'Pink') "바뀐 상점명"
from food_orders where restaurant_name like '%Blue Ribbon%'

substr = substring : 문자 자르기

substr(컬럼, 시작 위치, [글자 수])# 서울특별시 -> 서울 (1번째부터 2글자)
select addr "원래 주소",
       substr(addr, 1, 2) "시도"
from food_orders where addr like '%서울특별시%'

concat : 문자 합치기

붙일 수 있는 문자의 종류

  • 컬럼 / 한글 / 영어 / 숫자 / 특수문자
concat(붙이고 싶은 값1, 붙이고 싶은 값2, 붙이고 싶은 값3, .....)

select restaurant_name "원래 이름",   
       addr "원래 주소",
       concat('[', substring(addr, 1, 2), '] ', restaurant_name) "바뀐 이름"
from food_orders where addr like '%서울%'

4. 조건문

IF

if(조건, 충족할 때, 충족하지 못할 때)select restaurant_name, cuisine_type "원래 음식 타입",
       if(cuisine_type='Korean', '한식', '기타') "음식 타입"
from food_orders

Case

case when 조건1 then(수식)1
     when 조건2 then(수식)2
     else(수식)3
endselect cuisine_type,
       case when (cuisine_type='Korean') then '한식'
       when cuisine_type in('Japanese', 'Chinese') then '아시아'
       else '기타'
       end as "음식 타입"
from food_orders


📜 다음 학습 목표

  • SQL 강의 마무리
  • 선택 학습 SQL 진행

0개의 댓글