I have a hypothetical table “users” with the columns
- user_id (auto incremented)
- name
- foo
- bar
- last_updated
This table is updated multiple times per day. How can I query to get the last update, per user, per day, going back X days?
Example Data
1 John a b "2013-01-31 02:01:12"
2 Rich c d "2013-01-31 22:41:12"
3 John e f "2013-01-31 22:01:15"
4 Rich g h "2013-02-01 16:01:12"
5 John i j "2013-02-01 22:21:12"
6 Rich k m "2013-02-01 22:21:12"
Desired Return Set:
2 Rich c d 2013-01-31
3 John e f 2013-01-31
5 John i j 2013-02-01
6 Rich k m 2013-02-01
I am able to get the last updated per user overall with the following query, it’s applying it to each day that I am struggling with.
SELECT u1.*
FROM users u1
LEFT JOIN users u2
ON (u1.name = u2.name AND u1.user_id < u2.user_id)
WHERE u2.user_id IS NULL
First of all the table name
usersis very confusing, since these aren’t the users but the logins.Beyond that you’re on the right way. You just need to add a comparison on the date in the join.
See it work in this SQL fiddle.