简体   繁体   English

SQL - 检索过去7天的最后一天记录

[英]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. 现在我需要检索过去30天内每天的最新记录。

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. 由于每天有24条记录,所以我不知道如何仅在当天拉出最新记录。 Any help would be appreciated. 任何帮助,将不胜感激。

Step 1 - Break them into groups by day. 第1步 - 白天将它们分成几组。
Step 2 - Select the timestamp of the last entry for each group. 步骤2 - 选择每个组的最后一个条目的时间戳。
Step 3 - Go back and get the records that match those timestamps. 第3步 - 返回并获取与这些时间戳匹配的记录。


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. 注意:这假定每个记录在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. 如果它们不是唯一的,并且多个记录在任何给定的日期都是最新的,则返回所有绑定的记录。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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