[Tools]/SQL 이것저것

[MySQL] dayofweek() 함수로 요일 붙이기

pjw250 2024. 10. 7. 21:14
select dt, case dayofweek(dt)
		 when '1' then 'SUN'
		 when '2' then 'MON'
		 when '3' then 'TUE'
		 when '4' then 'WED'
		 when '5' then 'THU'
		 when '6' then 'FRY'
		 when '7' then 'SAT' else 'what' end as 'day'
	 ,avg(price) as avg_price
	 ,sum(price) as sum_price
	 ,count(price) AS cnt
from(	select substr(event_time,1,10) as dt, price
		from basic.com
		where event_type='purchase'
	)as a
group by 1;

 

위 예제는 Kaggle ecommerce data 2020년 02월 온라인 판매제품으로 실습하던 중 조원 중 한분이 발견한 함수이다.

2월 한달 동안의 데이터들 중 event_time에 일자를 서브쿼리로 받고 이것을 월,화,수,목,금 으로 받는 것이다.

두고두고 써먹자

** 참고로 SELECT 바로 앞 dt를 빼버리면 날짜별 요일이 아닌 모든 날짜의 요일로 압축/그룹핑을 수행한다.