Skip to content
Advertisement

MySQL group by week interval on Linux timestamps starting from Sunday

I have a table of users that have joined and the column that tracked the timestamp of when they joined is a UNIX timestamp.

I want to group them by a weeks time in seconds, 604800, but am running into a roadblock. The other searches use MySQL week, but that is not what I am after since those weeks are not always full at the end of the year and vary depending on starting day.

The query for Week grouping:

I want to group my users by timestamp starting from next Sunday down. So, it would be the following Sunday, and one week intervals backwards until I run out of records.

I have tried to FLOOR( joined / 604800 ) AS weekno but that is inaccurate since it starts from the earliest or latest record, and I need the week to start on Sunday, like:

Does anyone have any tips?

Sample data that I am looking for

Result:

Advertisement

Answer

Here’s what you want. This expression takes any unixtimestamp value and converts it to a DATETIME value that’s midnight on the Sunday of the week containing your unixtimestamp.

So this query should do the trick for you.

I like to use this stored function for the purpose. It’s easier to write and read your queries when you use it.

If you use the stored function you can write your query like this (https://www.db-fiddle.com/f/cbtf9rueAvtFNUxE1PS387/0)

If you want your weeks to start on Mondays, use -2 instead of -1 in the expression.

See this and this.

As a bonus, this technique honors your local timezone when figuring out the calendar week of any unixtimestamp.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement