공부하기/Database

SQL 기본 문법 복기 (2)

다섯자두 2024. 12. 27. 20:07

SQL 강의를 마저 들었다 !


REPLACE : 글자 대치하기

  • replace(컬럼, 대상 글자, 바뀔 글자)

 

CONCAT : 문자열 합치기

  • concat(합칠 문자열, 합칠 문자열, ...)
select concat('[',substr(addr,1,2),']',restaurant_name,' (',cuisine_type,')') "음식점",
		count(1) "주문 건수"
from food_orders
group by 1

 

SUBSTR : 원하는 위치의 글자만 가져오기

  • substr(컬럼, 시작 인덱스, 가져올 글자 수)
    • 시작 인덱스 >= 1
    • '가져올 글자 수'를 명시하지 않고 substr(컬럼, 시작 인덱스)로 적을 경우, 시작 인덱스부터 끝까지 가져옴

 

GROUP BY : select 절의 n번째 컬럼으로 묶기

group by 뒤에 n을 적어준다

select substr(email,10) "도메인", count(1) "고객 수", avg(age) "평균연령"
from customers
group by 1

 

조건문 IF : 단일 조건에 따른 처리

  • if(조건, true일 경우 값, false일 경우 값)

음식 타입이 'Korean'이라면 '한식'을, 다른 타입이라면 '기타'를 출력

select restaurant_name '음식점 이름', if(cuisine_type='Korean','한식','기타') '음식타입'
from food_orders

 

조건문 CASE : 여러 조건에 따른 처리

  • case when 조건1 then 값1 when 조건2 then 값2 else 값3 end

음식 타입이 'Korean'이라면 '한식'을, 'Japanese'나 'Chinese'라면 '아시아'를, 그외 다른 타입이라면 '기타'를 출력

select restaurant_name "음식점 이름", 
    case when cuisine_type="Korean" then "한식"
    when cuisine_type in ("Japanese","Chinese") then "아시아"
    else "기타" end "음식 타입"
from food_orders

 

10세 이상 30세 미만의 고객 정보 분류하기

select case when (age between 10 and 19) and (gender='male') then '10대 남성'
	 		when (age between 10 and 19) and (gender='female') then '10대 여성'
	 		when (age between 20 and 29) and (gender='male') then '20대 남성'
	 		when (age between 20 and 29) and (gender='female') then '20대 여성'
	 		end "고객 분류",
 		name,
 		age,
 		gender
from customers
where age between 10 and 29

 

서브쿼리 사용하기

서브쿼리가 필요한 경우

  1. 여러번의 연산을 수행할 필요가 있을 때
  2. 조건문에 연산 결과를 사용해야 할 때
  3. 조건에 Query 결과를 사용하고 싶을 때
select column1, special_column
from
    ( /* subquery */
    select column1, column2 special_column
    from table1
    ) a
⚠️ from절에 서브쿼리를 사용하는 경우, 서브쿼리에 별명을 지정해주어야한다.

 

JOIN 사용하기