출처: 패스트 캠퍼스 - 한 번에 끝내는 데이터 분석 초격차 패키지 Online.
원하는 컬럼 추가하기: case when
case when 조건 then 결과값 else(=그 외 조건) 결과값 end
case when 컬럼 in 조건 then 결과값 else(=그 외 조건) 결과값 end
목차 | |
1. 성별 컬럼 추가하기 | : case when |
2. 연령대로 그룹화하기 | |
3. 특정 키워드의 상품 vs 나머지 상품의 매출액 비교하기 | |
4. top3 카테고리 vs 그 외 상품의 매출액 비교하기 |
: case when in |
1. 성별 컬럼 추가하기
01) case when 문법 쿼리
case whe 조건1 then 결과값1
when 조건2 then 결과값2
else(=그 외 조건) 결과값
end
02) 쿼리문 작성
select distinct case when gender = 'M' then '남성' when gender = 'F' then '여성' else 'NA' end as gender
from user_info ui
>>>> 해석 >>>>
성별(gender)이 남자('M')일 때 '남성'표시
성별(gender)이 여자('F')일 때 '여성'표시

03) 정리.ver
select distinct case when gender = 'M' then '남성'
when gender = 'F' then '여성'
else 'NA'
end as gender
from user_info ui

2. 연령대 그룹 만들기 (20,30,40대)
01) 연령대 별 매출액 조회하기
select ui.age_band, sum(gmv) as gmv
from online_order oo
left join user_info ui on oo.userid = ui.userid
group by 1

02) 다양하게 나눠져 있는 연령대를 그룹화하기
*조건
20-24, 25-29 = 20s
30-34, 35-39 = 30s
40-44 = 40s
나머지는 'NA'로 변환
* 쿼리문작성
case when ui.age_band = '20~24' then '20s'
when ui.age_band = '25~29' then '20s'
when ui.age_band = '30~34' then '30s'
when ui.age_band = '35~39' then '30s'
when ui.age_band = '40~44' then '40s'
else 'NA'
end as age_group

3. 특정 키워드가 담긴 상품과 그렇지 않은 상품의 매출 비교하기
01) 특정 키워드가 담긴 상품과 그렇지 않은 상품 분류
*쿼리문 작성
select item_name,
case when item_name like '%깜찍%' then '깜찍컨셉' >>> 특정 키워드 (깜찍)
when item_name like '%시크%' then '시크컨셉' >>> 특정 키워드 (시크)
when item_name like '%청순%' then '청순컨셉' >>> 특정 키워드 (청순)
when item_name like '%기본%' then '기본컨셉' >>> 특정 키워드 (기본)
else '미분류' >>> 그렇지 않은 키워드
end as item_consept
from item

02) 특정 키워드 상품과 none 키워드 상품의 매출액 비교
* 쿼리문 작성 (join, case when 등)
select
case when item_name like '%깜찍%' then '깜찍컨셉'
when item_name like '%시크%' then '시크컨셉'
when item_name like '%청순%' then '청순컨셉'
when item_name like '%기본%' then '기본컨셉'
else '미분류'
end as item_consept
,sum(gmv) as gmv >>> 매출액
from online_order oo
join item i on oo.itemid = i.id
group by 1
order by 2 desc >>> 매출액이 큰 순서로 정렬

4. top3 카테고리와 그 외 상품의 매출액 비교하기
01) 카테고리별 매출액 조회하기
top3 제품을 알기 위해서 join을 사용하여 상품별 매출액 비교하기

02) top3 카테고리와 그 외 상품의 매출액 비교하기
* top3 카테고리: 스커트, 티셔츠, 원피스
* 쿼리문 작성
case when cate1 in ('스커트','티셔츠', '원피스') then 'TOP3'
else '기타'
end

'데이터 교육 > SQL' 카테고리의 다른 글
[SQL] 12. 사칙연산(할인률, 판매가, 이익률) 계산하기 (0) | 2023.05.29 |
---|---|
[SQL] 11. 날짜 관련 함수 활용하기 (0) | 2023.05.29 |
[SQL] 09. 원하는 형식으로 컬럼 가공하기 (0) | 2023.05.29 |
[SQL] 08. join절 (0) | 2023.05.29 |
SQL 기본 문법 정리 (0) | 2023.05.24 |