简体   繁体   中英

SQL - retrieve last record of day for the last 7 days

I am inserting a record every hour into my table. Now I need to retrieve the most recent record of each day for the last 30 days.

Here is my table:

pl_scores: {
  score_id: 'BIGINT(255) PRIMARY KEY AUTO_INCREMENT'
, pid: 'INT(100)'
, score: 'INT(255)'
, rank: 'INT(50)'
, city_cnt: 'INT(10)'
, updatedAt: 'DATETIME'
}

Since there is 24 records for each day I am at a loss as to how to pull the most recent only for that day. Any help would be appreciated.

Step 1 - Break them into groups by day.
Step 2 - Select the timestamp of the last entry for each group.
Step 3 - Go back and get the records that match those timestamps.


SELECT
  pl_scores.*
FROM
  pl_scores
INNER JOIN
  (SELECT MAX(updatedAt) AS maxUpdatedAt FROM pl_scores GROUP BY DATE(updatedAt)) as Lookup
    ON Lookup.MaxUpdatedAt = pl_scores.updatedAt

Note: This assumes that each record has a different value in updatedAt. If they're not unique, and multiple records are tied for being the most recent on any given day, all the tied records are returned.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM