CASE 기본 형식
SELECT
CASE
WHEN TRUE THEN '참입니다'
ELSE '거짓입니다.'
END
WHEN
의 문이 참일때만 일어남case
문 안에 조건이 참인지 확인ELSE
문이 일어남end
로 탈출여러 조건일 경우
CASE
안에 조건을 여러개 써주면 됨SELECT
CASE
WHEN 3=1 THEN '참1입니다'
WHEN 3=2 THEN '참2입니다'
WHEN 3=3 THEN '참3입니다'
ELSE '거짓입니다.'
END
if
문과 마찬가지로 첫 조건이 만족하지 않으면 바로 아래 조건으로 내려감# cost 비용
# 20달러 이하 -> 저비용
# 20 초과 ~ 50 달러 이하 -> 저비용
# 50 달러 이상 -> 고비용
# 없음
select
id,
cost,
case
when cost <= 20 then '저비용'
when cost <= 50 then '중비용'
when cost > 50 then '고비용'
else '없음'
end as cost_level
from `thelook_ecommerce.products`
CASE문이 ELSE없이 거짓일 경우
null
값으로 나타남select
case
when false then 'true'
end # null
null
값인 것을 이용해서 count
에 사용해주면됨
예시
select
extract(year from created_at) as year,
count (case when gender = 'F' then id end) as female,
count (case when gender = 'M' then id end) as male,
count(id) as total
from `thelook_ecommerce.users`
group by year
연도별 연령대별 가입자 수
select
extract(year from created_at) as year
count(case when age between 10 and 19 then id end) as age_10s
count(case when age < 30 then id end) as age_20s
count(case when age < 40 then id end) as age_30s
count(case when age < 50 then id end) as age_40s
count(case when age < 60 then id end) as age_50s
from `thelook_ecommerce.users`
select
extract(year from created_at) as year,
count(case when age between 10 and 19 then id end) as age_10s,
count(case when age between 20 and 29 then id end) as age_20s,
count(case when age between 30 and 39 then id end) as age_30s,
count(case when age between 40 and 49 then id end) as age_40s,
count(case when age between 50 and 59 then id end) as age_50s,
count(id) as total
from `thelook_ecommerce.users`
group by year
연도별 분기별 가입자수
-- YEAR Q1 Q2 Q3 Q4 TOTAL
-- 2019 111 111 111 111 444
-- 2020 111 111 111 111 444
-- 2021 111 111 111 111 444
-- 2022 111 111 111 111 444
이런식으로 나오게 해!!
🐰져니 코드
select
extract(year from created_at) as year,
count(case when extract(QUARTER from created_at)=1 then id end) as Q1,
count(case when extract(QUARTER from created_at)=2 then id end) as Q2,
count(case when extract(QUARTER from created_at)=3 then id end) as Q3,
count(case when extract(QUARTER from created_at)=4 then id end) as Q4,
count(id) as total
from `thelook_ecommerce.users`
group by year
order by year
🧑🏫 강사님 코드랑 같음