I have a query which calculates the total hours worked for the current week by task:
SELECT name AS 'Task Name'
, sum(hours) AS `Total Hours`
FROM time_records
WHERE yearweek(record_date, 3) = yearweek(now(), 3)
GROUP BY
weekday(record_date), name
The WHERE clause specifies the current week:
WHERE yearweek(record_date, 3) = yearweek(now(), 3)
This data is displayed as a table using the MySQL query and a PDO statement.
I would now like to add an option for the viewer to see the previous week of data by clicking a link under the table (e.g., “Previous Week”). In order to show that data, I would need to update the WHERE clause to query for the previous week:
WHERE yearweek(record_date, 3) = yearweek(now(), 3) - 1
I’m wondering what the best way to do this is? I would prefer to keep just one version of the overall query. One thought is to use PHP to add the “- 1” to the query, such as:
WHERE yearweek(record_date, 3) = yearweek(now(), 3) <?php if (prev) {echo "- 1" ;} ?>
I think this should work, but how can I determine the prev condition? Should I make the entire query be inside a function so that for the default it can be “Time_hours(0)” and for the previous it can be “Time_hours(1)” – or is there some better way?
I’m concerned about keeping the code manageable and following best practices. Any tips would be appreciated. Thanks!
I suggest you try a query that has a parameter for the number of weeks ago you want to process. YEARWEEK is a bad choice for weekly processing because it handles end-of-year rollovers poorly.
Try this, if your weeks begin on Sunday. This will give the current week.
Fiddle: http://sqlfiddle.com/#!2/4c487/1/0
If you want, let’s say, one week ago, change
- interval 0 weekto- interval 1 weekin your query. See this fiddle. http://sqlfiddle.com/#!2/4c487/2/0You can put an an arbitrary number of weeks ago, even weeks that span year ends. See here for
interval -42 weekfor example. http://sqlfiddle.com/#!2/4c487/3/0The expression
FROM_DAYS(TO_DAYS(CURDATE()) -MOD(TO_DAYS(CURDATE()) -1, 7))rounds the current date down to the previous Sunday. If you want to round it to the previous Monday, useFROM_DAYS(TO_DAYS(CURDATE()) -MOD(TO_DAYS(CURDATE()) -2, 7)). For example: http://sqlfiddle.com/#!2/4c487/8/0