首页 > 解决方案 > 如何获取每个 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

但我只有一排

标签: sqlpostgresql

解决方案


使用distinct on

select distinct on (user_id) rh.*
from ratio_history rh
order by user_id, year desc, month desc;

distinct on是一个非常方便的 Postgres 扩展。它为括号中的键值返回一行?哪一行,它是基于排序条件的第一行。请注意,排序条件需要以括号中的表达式开头。


推荐阅读