let’s assume I have this numrequest table. it has these fields: id, id_user, time(timestamp)
I want to count the records for a specific $id_user grouped by week.
I know how to count the records for a period of time.
$past=time()-$totalSecondsInAweek
$query='SELECT COUNT(1) as counta
from numrequest
WHERE time >'.$past.'
AND WHERE id_user='.$id_user;
but how to do that so it counts per each week since the first input regarding a specific $id_user
My main doubt, and possible unrelated to the question itself, is why are you doing this?
Are you trying to get records only from the last 7 days?
If that is the case, please, try this in your sql code:
WHERE time > date_sub(curdate(), INTERVAL 7 DAY)In my solution I’ll be removing this condition because I don’t understand it and I just can’t link it to grouping by week.
Now, to your answer. My bet is that you don’t want just to group by week. You want to group by the pair (Year-Week). If you don’t do this, you’ll group in the week number 0 both dates: “2011-01-01” and “2012-01-01”. So, I assume you would like to have the previous data displayed this way:
Rather than:
So, here is the SQL code:
Here is an example
If you would like to have the year and week in only one column, you can try this (which I think will be faster than a CONCAT(year, week)):
Here is an example
Note: If you want your week numbers to start in 0 or to choose whether it should start on monday or sunday check the official documentation.
Hope this helps.