How can I select one, most recent NID, per every 7 days, per UID, starting count back from today.
If today is July 11, the following table
+-----+------------+-----+
| NID | timestamp | UID |
+-----+------------+-----+
| 1 | 1341719851 | 8 | //July 7
| 2 | 1341115051 | 8 | //July 1
| 3 | 1341547051 | 8 | //July 6
| 4 | 1341719851 | 8 | //July 8
| 5 | 1341979051 | 8 | //July 11
| 6 | 1341806251 | 9 | //July 9
| 7 | 1341460651 | 9 | //July 5
| 8 | 1341892651 | 9 | //July 10
+-----+------------+-----+
Will output this:
+-----+------------+-----+
| NID | timestamp | UID |
+-----+------------+-----+
| 2 | 1341115051 | 8 | //July 1
| 5 | 1341979051 | 8 | //July 11
| 8 | 1341892651 | 9 | //July 10
+-----+------------+-----+
In the last 7 days, most recent NID for each user is '5' and '8', in the prior 7 days, most recent NID is '2', and so on…
I’m assuming, Group By will do the trick; but I don’t have a clue where to start.
UPDATE
This is the query that worked, based on the top answer:
SELECT nid, timestamp, uid, weeks_ago
FROM (
SELECT nid, timestamp, uid, FLOOR(
(UNIX_TIMESTAMP()- timestamp)/604800
) weeks_ago
FROM `table`
ORDER BY timestamp DESC
) x
GROUP BY uid, weeks_ago
1 Answer