简体   繁体   English

Select mysql 中带有 group by 子句的日期和时间列的最新记录

[英]Select latest record with date and time column with group by clause in mysql

I have this table from which I have to select the latest row on the basis of date and time column for each checkpost我有这张表,我必须根据每个检查站的日期和时间列 select 最新行

在此处输入图像描述

I have tried the following queries but not returning the latest data for each checkpost.我尝试了以下查询,但没有返回每个检查站的最新数据。

SELECT checkpost_id,current_rate,date,time FROM revisionrates 
WHERE date IN (SELECT max(date) FROM revisionrates GROUP BY checkpost_id)

The expected output is预期的 output 是

在此处输入图像描述

You can use window functions:您可以使用 window 函数:

select rr.*
from (select rr.*,
             row_number() over (partition by checkpost_id order by date desc, time desc) as seqnum
      from revisionrates rr
     ) rr
where seqnum = 1;

This requires MySQL 8.0.这需要 MySQL 8.0。 In earlier versions of MySQL, this is a bit trickier, but one method uses tuples在 MySQL 的早期版本中,这有点棘手,但一种方法使用元组

select rr.*
from rr
where (date, time) in (select rr2.date, rr2.time
                       from revisionrates rr2
                       where rr2.checkpoint_id = rr.checkpoint_id
                       order by rr2.date desc, rr2.time desc
                       limit 1
                      );

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

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