首页 > 解决方案 > 获取具有不同 id 的每一行的最后一个条目

问题描述

我正在使用10.4.11-MariaDB.

我有下表:

| id    | organization | reportDate | pctHeld | position   | value        | created_at          | updated_at          |
|-------|--------------|------------|---------|------------|--------------|---------------------|---------------------|
| 45829 | Org 1        | 1601424000 | 0.0204  | 346699497  | 40151268747  | 2020-11-21 01:15:18 | 2020-11-21 01:15:18 |
| 43452 | Org 2        | 1601424000 | 0.0124  | 210830547  | 24416285648  | 2020-11-20 01:13:32 | 2020-11-20 01:13:32 |
| 43450 | Org 1        | 1601424000 | 0.0204  | 346699497  | 40151268747  | 2020-11-20 01:13:32 | 2020-11-20 01:13:32 |
| 40947 | Org 1        | 1601424000 | 0.0204  | 346699497  | 40151268747  | 2020-11-19 01:04:54 | 2020-11-19 01:04:54 |
| 29211 | Org 3        | 1601424000 | 0.0098  | 166053767  | 19230686756  | 2020-11-16 00:49:26 | 2020-11-16 00:49:26 |
| 29203 | Org 2        | 1601424000 | 0.0629  | 1069771045 | 123890184721 | 2020-11-16 00:49:26 | 2020-11-16 00:49:26 |
| 26963 | Org 3        | 1601424000 | 0.0098  | 166053767  | 19230686756  | 2020-11-15 00:49:38 | 2020-11-15 00:49:38 |

我试图得到唯一的最后一行 - 基于reportDate我的表,但是,我得到了相同的结果:

select * from organization 
inner join (
    select `organization`, max(`reportDate`) as MaxDate
    from ownership
    group by `organization`
) tm on ownership.organization = tm.organization and ownership.reportDate = tm.MaxDate

有什么建议我做错了吗?

感谢您的回复!

标签: mysqlsqlsubquerygreatest-n-per-group

解决方案


如果你想要每行的最新行organization,你可以使用窗口函数,这些函数在 MariaDB 10.3 版本中可用:

select *
from (
    select o.*, 
        row_number() over(partition by organization order by reportdate desc, updated_at desc) rn
    from ownership o
) o
where rn = 1

在早期版本中,一个选项使用相关子查询。假设这id是您的表的主键:

select *
from ownership o
where id = (
    select o1.id 
    from ownership o1
    where o1.organization = o.organization
    order by o1.reportdate desc, o1.updated_at desc
    limit 1
)

推荐阅读