Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to group by week specifying end of week day?

Tags:

sql

mysql

I need to run a report grouped by week. This could be done by using group by week(date) but the client wants to set the day of the week that marks the end of week. So it can be Tuesday, Wednesday etc. How can I work this into a group by query?

The datetime column type is unix timestamp.

like image 498
Pentium10 Avatar asked Dec 16 '25 19:12

Pentium10


1 Answers

The WEEK() function takes an optional second parameter to specify the start of the week:

This function returns the week number for date. The two-argument form of WEEK() enables you to specify whether the week starts on Sunday or Monday and whether the return value should be in the range from 0 to 53 or from 1 to 53.

However, it can only be set to Sunday or Monday.


UPDATE: Further to the comments below, you may want to consider adding a new column to your table to act as a grouping field, based on WEEK(DATE_ADD(date INTERVAL x DAY)), as suggested in the comments. You may want to create triggers to automatically generate this values whenever the date field is updated, and when new rows are inserted. You would then be able to create a usable index on this new field as required.

like image 138
Daniel Vassallo Avatar answered Dec 19 '25 14:12

Daniel Vassallo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!