mysql - 获取具有不同 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
有什么建议我做错了吗?
感谢您的回复!
解决方案
如果你想要每行的最新行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
)
推荐阅读
- laravel - 如何使用 Laravel 和 JQuery Masonry 更改 Bootstrap 网格中的列数
- c++ - 如何让系统在十六进制数字之前打印 0x 和在八进制数字之前打印 0?
- javascript - Recorder.js 在本地主机上工作正常,但在服务器上不工作
- ios - 在情节提要中使用材质样式时,iOS 13.0 警告之前的系统模糊样式
- python - Keras 不能使用回调来存储检查点
- python - 返回并打印输入的平均值
- r - 如何解决R中的这个积分?
- r - 如何更改关于 3 组的列的值
- python-3.x - 使用 PyDictionary 打印出 dictionary.meaning() 输出时遇到问题
- python - 获取用僧伽罗语编写的推文并保存在 csv 文件中