Lets say I have this query:
select
week(sr.transactionDate) AS week_number,
sum(sr.digitalEarnings)
from
sales_report as sr
where `sr`.`transactionDate` BETWEEN '2022-05-01' AND '2022-12-31'
group by week_number
order by week_number;
Which returns data like so:
I know this is the "week in the year" number but I’m actually trying to get the data divided into weeks starting from 1. i.e Week 1 in this period, week 2 in this period etc.
How would I achieve this?
3
Answers
how about using
ROW_NUMBER()
although this is only available in v8 and above:https://dev.mysql.com/doc/refman/8.0/en/window-function-descriptions.html#function_row-number
You could just use some common sense math:
Or this:
First one will start numbering weeks from 1, the second one has potential of starting from, e.g. 3 if filtered data starts from 2022-05-15. Both queries can have gaps for wholly missing weeks.
You can calculate week number directly from the transaction date. Assuming you have left the default_week_format system variable unchanged, you are doing weeks starting with Sunday; adjust your range start date to find the Sunday on or before, and count the weeks from that to the transaction date, adding one to start with week 1, not week 0:
I strongly suggest not using week() at all; its behavior across years or near the beginning or end of years is usually not friendly for reporting purposes. Especially subtracting or comparing two week values can be problematic.