首页 > 解决方案 > SQL 查询以获取该用户的最新记录

问题描述

我有一个 MySQL 数据库,我需要一些帮助来查询表中的数据。

// Table
id              INTEGER,
column1         VARCHAR,
completiondate  DATETIME

// Sample data
(101, 'a', '2020-03-20 12:00:00')
(101, 'b', '2020-03-21 12:00:00')
(101, 'c', '2020-03-22 12:00:00')
(101, 'c', '2020-03-23 12:00:00')
(101, 'd', '2020-03-24 12:00:00')
(102, 'a', '2020-03-20 12:00:00')
(102, 'b', '2020-03-21 12:00:00')

在这里,我想查看该特定用户的所有记录,并仅显示 中找到的重复项中的最新记录column1

用户的预期输出101

(101, 'a', '2020-03-20 12:00:00')
(101, 'b', '2020-03-21 12:00:00')
(101, 'c', '2020-03-23 12:00:00')
(101, 'd', '2020-03-24 12:00:00')

我是 SQL 新手。如果有人能对此提供任何见解,那就太好了。

提前致谢!

标签: mysqlsqldatabasegreatest-n-per-group

解决方案


您可以使用子查询进行过滤:

select t.*
from mytable t
where 
    t.id = 101
    t.completiondate = (
        select max(t1.completiondate) 
        from mytable t1 
        where t1.id = t.id and t1.id = t.id and t1.column1 = t.column1
    )

或者,在 MySQL 8.0 中,您可以使用窗口函数rank()

select *
from (
     select t.*, rank() over(partition by id, column1 order by completiondate desc) rn
     from mytable t
     where id = 101
) t
where rn = 1

请注意,对于此数据集,您还可以使用简单的聚合:

select id, column1, max(completiondate) completiondate
from mytable
where id = 101
group by id, column1

推荐阅读