This is my first post on stackoverflow, although I’ve used it as a reference for a long time. So thanks for all the guidance you’ve provided me in the past. I really appreciate it. Here is my issue:
I have two tables, one called USERS and one called SIGNIN
USERS
-----------------
userid | password
SIGNIN
--------------
suserid | date
I would like to count the number of times that a user has signed in over the period of the last week.
Here’s what I’ve got:
SELECT userid, password FROM USERS JOIN (SELECT suserid, COUNT(*) AS logins
FROM signin
WHERE WEEKOFYEAR(date) = WEEKOFYEAR(CURDATE()) && signin.suserid = users.userid)
GROUP BY userid
I just can’t wrap my head around how to JOIN a subquery and make it count each individuals’ logins (date column) and return an individualized number for each individual. I know that query is totally jacked up but I’m just at that point, you know, where I’ve become so confused that I just need some guidance.
Any help and direction would be fantastic! I’ve read so many pages to no avail. Thanks, in advance!
** and thank you for the edits. They’ll help in the future when I post again.
Don’t try to do a subquery, just do the join and group by user id. Also, you want YEARWEEK so you are matching both the year and week, not just the week from any year.
left join instead of inner join if you want results of 0 for users who haven’t signed in.
This follows what I assume is your intent of “last week” meaning the week of the current date (by default starting Sunday, but see the optional mode parameter to yearweek).
Note that the users table here is completely optional; you could just do:
but I’m guessing you may be getting other columns from user or wanting to exclude signins for deleted users.