원하는 형식으로 colume 가공
-- 숫자를 문자로 바꿔주기
select dt, cast(dt as varchar) as yyyymmdd
from online_order oo
-- 문자열 컬럼에서 일부만 잘라내기
select dt, left(cast(dt as varchar), 4) as yyyy
from online_order oo
-- 문자열 컬럼에서 일부만 잘라내기
select dt, left(cast(dt as varchar), 4) as yyyy,
substring(cast(dt as varchar), 5, 2) as mm,
right(cast(dt as varchar), 2 ) as dd
from online_order oo
-- yyyy-mm-dd 형식으로 이어주기 #1
select dt,
concat(
left(cast(dt as varchar), 4) as yyyy, '-'
substring(cast(dt as varchar), 5, 2) as mm, '-'
right(cast(dt as varchar), 2 ) ) as yyyymmdd
from online_order oo
-- yyyy-mm-dd 형식으로 이어주기 #2
select dt,
left(cast(dt as varchar), 4) as yyyy || '-' ||
substring(cast(dt as varchar), 5, 2) as mm || '-' ||
right(cast(dt as varchar), 2 ) as yyyymmdd
from online_order oo
-- null 값인 경우 임의 값으로 바꿔 주기 #1
select coalesce (ui.gender, 'NA') as gender
from online_order oo
left join user_info on oo.userid = ui.userid
-- null 값인 경우 임의 값으로 바꿔 주기 #2
select coalesce(ui.gender, 'NA') as gender, coalesce(ui.age_band) as age_band,
sum(oo.gmv) as gmv
from online_order oo
left join user_info ui on oo.userid = ui.userid
group by 1,2
order by 1,2
-- 내가 원하는 컬럼 추가해보기
select distinct case when gender = 'M' then '남성' when gender = 'F' then '여성' else 'NA' end as gender
from user_info ui
-- 연령대 그룹 만들어보기(20대, 30대, 40대)
select
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
, sum(gmv) as gmv
from online_order oo
left join user_info ui on oo.userid = ui.userid
group by 1
order by 1
-- Top3 카테고리와 그 외 상품의 매출액 비교하기
select
case when cate1 in ('스커트', '티셔츠', '원피스') then 'TOP3'
else '기타' end as item_type
, sum(gmv) as gmv
from online_order oo
join item i on oo.itemid = i.id
join category c on i.category_id = c.id
group by 1
order by 2 desc
-- 특정 키워드가 담긴 상품과 그렇지 않은 상품의 매출 비교하기 (+item 갯수도 확인하기)
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_concept
,sum(gmv) as gmv
from online_order oo
join item i on oo.itemid = i.id
group by 1
order by 2 decs
날짜 관련 함수
아래 함수는 postgre sql 기준으로 작성된 함수 이므로, 해당 함수는 sql의 종류마다 각기 다른 모습을 띄게 됩니다.
-- 오늘을 나타내는 기본 구문
select now()
select current_date
select current_timestamp
-- 날짜 형식에서 문자 형식으로 변환하기
-- 해당 부분은 다른 sql과 비슷하기에 외워두면 좋다
select to_char(now(), 'yyyymmdd')
select to_char(now(), 'yyyy-mm-dd')
-- c) 날짜 더하기 / 빼기
select now() + interval '1 month'
select now() + interval '-1 month'
-- d) 날짜로 부터 연도, 월, 주 확인하기
select data_part('month' , now())
select data_part('day' , now())
-- d) 최근 1년동안의 매출액 확인하기
select *
from gmv_trend gt
where cast(yyyy as varchar) || cast(mm as varchar)
>= cast(date_part('year', now() - interval '1 year') as varchar) || cast(date_part('month', now() - interval '1 year') as varchar)
order by 2,3
사칙 연산
--- 3. 할인율, 판매가, 이익률 계산하기
select *,
cast(discount as numeric) / gmv as discount_rate,
gmv - discount as paid_amount,
cast(product_profit as numeric) / gmv as product_magin,
cast(total_profit as numeric) / gmv as total_margin
from online_order oo
select c.cate1
round(sum(cast(discount as numeric),2) / sum(gmv)) as discount_rate,
sum(gmv - discount as paid_amount),
sum(cast(product_profit as numeric)) / sum(gmv) as product_magin,
sum(cast(total_profit as numeric)) / sum(gmv) as total_margin
from online_order oo
join item i on oo.itemid = i.id
join category c on i.category_id = c.id
group by 1
order by 3 desc
-- round(소수, 반 올림할 자릿수)
-- 4. 고객 관점에서의 분석(인당 평균 구매 수량 / 인당 평균 구매금액 )
-- 인당 구매 수량이 높은 상품은?
-- 인당 평균 구매 수량 = 총 판매 수량 / 총 고객 수
-- 인당 평균 구매 금액 = 총 구매 금액 / 총 고객 수
select i.item_name
, sum(unitsold) as unitsold
, count(distinct userid) as user_count -- 중복값 해제시에 쓸수 잇는 distinct 옵션
from online_order oo
join item i on oo.itemid = i.id
-- 인당 구매 금액이 높은 성/연령대는?