sql - 如何获取每个 user_id 的最后一个值(postgreSQL)
问题描述
用户的当前比率是他在“比率历史”表中最后插入的比率
user_id | year | month | ratio
例如,如果 ID 为 1 的用户有两行
1 | 2019 | 2 | 10
1 | 2019 | 3 | 15
他的比例是15。
开发表中有一些切片
user_id | year | month | ratio
1 | 2018 | 7 | 10
2 | 2018 | 8 | 20
3 | 2018 | 8 | 30
1 | 2019 | 1 | 40
2 | 2019 | 2 | 50
3 | 2018 | 10 | 60
2 | 2019 | 3 | 70
我需要一个查询,它将按 user_id 及其最后一个比率选择分组的行。
作为请求的结果,应选择以下条目
user_id | year | month | ratio
1 | 2019 | 1 | 40
2 | 2019 | 3 | 70
3 | 2018 | 10 | 60
我尝试使用此查询
select rh1.user_id, ratio, rh1.year, rh1.month from ratio_history rh1
join (
select user_id, max(year) as maxYear, max(month) as maxMonth
from ratio_history group by user_id
) rh2 on rh1.user_id = rh2.user_id and rh1.year = rh2.maxYear and rh1.month = rh2.maxMonth
但我只有一排
解决方案
使用distinct on
:
select distinct on (user_id) rh.*
from ratio_history rh
order by user_id, year desc, month desc;
distinct on
是一个非常方便的 Postgres 扩展。它为括号中的键值返回一行?哪一行,它是基于排序条件的第一行。请注意,排序条件需要以括号中的表达式开头。
推荐阅读
- scala - scala中的安全/不安全模式
- google-apps-script - 通过 AdSense 帐户生成报告并将结果输出到电子表格
- python - 使用 MagicMock 作为自己的返回值?
- ios - 如何以编程方式打开/关闭 IOS / iphone / ipad 的限制?
- azure-sql-database - 为什么我无法选择自己作为 Azure SQL 的 Active Directory 管理员?
- c# - CloseQuoteRequest 抛出异常
- javascript - CustomElements 在启用 about:config 属性的 Firefox 中不起作用
- angularjs - 有序列表在 IE 中使用 ng-repeat 无法按预期工作
- google-maps - Google Places API - 文本搜索不返回特定地点,即使地点详细信息查询有效
- kubernetes - 干燥所有依赖于非常相似的 init-container 的部署的最佳方法