How to extract grouped data for the week using postgresql. Using sunday as the starting day of the week.
The main problem is how to make the week count from Sunday instead of Monday
How to extract grouped data for the week using postgresql. Using sunday as the starting day of the week.
The main problem is how to make the week count from Sunday instead of Monday
2
Answers
Yes it is possible. Use date_bin function. It is available in PG version 14 and onwards.
Here is an implementation for versions prior to PG14.
An illustration:
Alternatively, you can use
date_trunc
on any version. When you truncate by week it will use Monday, but that can be resolved by adding a day so that Sunday dates roll to the next week:When you render the final output, just be sure to subtract the day from the field (no need to do that in the group-by):
If
my_date
is a timestamp (below would also work for a date), then:instead of:
You can also encapsulate this into a function, but it seems overkill unless you are using this all over the place.