I like the week function in MySQL, but in my situation, I wanted to know which week of the month a row was in. I utlized this solution:
where run_date
is a timestamp like 2021-02-25 00:00:00
concat (
date_format(run_date, '%Y-%m'),
' wk ',
(week(run_date,1) - ( week(date_format(run_date, '%Y-%m-01')) - 1))
) as formatted_date
This outputs:
2021-02-23 ---> 2021-02 wk 4
2021-02-25 ---> 2021-02 wk 4
2021-02-11 ---> 2021-02 wk 2
2021-03-02 ---> 2021-03 wk 1
The idea behind this is that I want to know (with relative certainty) which week of the month in question did the date occur?
So we concatenate:
date_format(run_date, '%Y-%m')
to get 2021-02
then we add the literal text string wk
then we use:
week(run_date, 1)
to get the week (1
to start Monday) of this record, (which would be 7
because 02/21/2021 is in the 7th week of the year, and we subtract whatever the week is on the 1st day of this same month - the week()
for 2021-02-01
is 5, because it is in the 5th week of the year:
(week(date_format(run_date, '%Y-%m-01'))
Unfortunately, this will start out the counting at 0, which people don't like, so we subtract 1 from the last part of the concatenation result so that the "week" start at 1.
TRUNC(date, 'DY' )
gets weeks with a Sunday start.'W'
gets a Monday start, at least in my system. – Wyattwyche