MySQL: Determining the First Day of a Week
Suppose you have a date, such as 2011-01-03, and want to obtain the first day of that week, which in this case is 2011-01-02. This is particularly pertinent to a query that groups data by weeks but encounters variations in the beginning dates of each week.
To determine the first day of a week, you can utilize one of the following MySQL functions:
Sunday as the First Day of the Week:
DATE_ADD(mydate, INTERVAL(1-DAYOFWEEK(mydate)) DAY)
Monday as the First Day of the Week:
DATE_ADD(mydate, INTERVAL(-WEEKDAY(mydate)) DAY);
In your specific query, you can modify the following line to select the first day of the week:
date(date_entered) as week, <-------This is what I want to change to select the first day of the week.
By incorporating one of the above functions, you can ensure that the beginning of each week aligns with your desired day, regardless of the actual date.
The above is the detailed content of How to Get the First Day of a Week in MySQL?. For more information, please follow other related articles on the PHP Chinese website!