SQL (Case When, with)

김혜민·2024년 3월 19일

SQL

목록 보기
14/21

1. Case when

  • 조건문을 단일/다중으로 활용하여 조건에 따른 결과값을 활용하여 새로운 컬럼을 생성
Case case_value
	when 조건 then 결과
    Else 결과
End as alias

ex) Case fruits -- 조건대상 Col 있을 때
		when 'apple' then '사과'
        when 'peach' then '복숭아'
        else '나머지'
    End as fruit_korean
    
    Case 
    	when fruit like '%starwberry' then '베리류'
        when fruit in ('Mango','Banana')
        	or fruit_cate = 'Tropical' then '열대과일류'
    End as fruit_sort

2. From

  • Original Table에서 사용하지 않을 Col이 많은 경우 연산량을 줄이기 위해서
  • Sub Query내에 연산이 필요한 경우
select col1, sum(avg_col3) as sum
from 
(
	select col1, col2, avg(col3) as avg_col3 -- Sub Query 내 연산
    from Original Table
    group by 1,2
) as sub

3. With

  • 해당 Query안에서 사용가능한 임시 테이블을 만드는 것
with Temp_Table_name as
	(
	  select ~
	  from Table
	)
  • 다양하게 활용 가능 Ex) left join, Union all..
profile
성장하는 주니어 데이터 분석가입니다!

0개의 댓글