본문 바로가기
분석/데이터분석

[MySQL] date_trunc 함수를 구현하자.

by 여우요원 2022. 8. 17.
반응형


date_trunc
라는 함수는 특정일자의 시작이 되는 unit 의 첫날을 가져오는 함수이다.

 

예를 들면 

date_trunc('week', '2022-08-05') 라고 하면 2022년 8월 5일이 있는 주(unit) 의 첫날인 '2022-08-01' 보여준다.

date_trunc('month', '2022-04-25') 라고 하면 2022년 4월 25일이 있는 월(unit) 의 첫날인 '2022-04-01'을 출력한다.

 

그런데 MySQL 에서는 안타깝게도 date_trunc 함수를 지원하지 않는다.

 

월의 첫날은 date_trunc 함수를 사용하지 않아도 구하는 것이 어렵지는 않지만, 주의 첫날을 구하는 것은 까다로울 수 있다.

그래서 아래와 같이 응용을 하여 구해볼 수 있다.

select STR_TO_DATE(CONCAT(YEARWEEK(now(), 7), ' Monday'), '%X%V %W')

여기에서는 월요일을 주의 시작으로 한다.

 

주(week) 의 정의 대해서는 다르게 생각할 수 있는데 아래의 yearweek 함수 사용법을 고려하여 수정하여 사용할 수 있다.

[ Syntax ]
YEARWEEK(date, firstdayofweek)

** firstdayofweek
Optional. Specifies what day the week starts on. Can be one of the following:

 0 - First day of week is Sunday
 1 - First day of week is Monday and the first week has more than 3 days
 2 - First day of week is Sunday
 3 - First day of week is Monday and the first week has more than 3 days
 4 - First day of week is Sunday and the first week has more than 3 days
 5 - First day of week is Monday
 6 - First day of week is Sunday and the first week has more than 3 days
 7 - First day of week is Monday

 

반응형