如何获取每个用户id的最后一个值(postgreSQL)

如何获取每个用户id的最后一个值(postgreSQL),sql,postgresql,Sql,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

用户的当前比率是他在表比率历史记录中最后插入的比率

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
我需要一个查询,该查询将按用户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:


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

谢谢!我尝试使用distinct,但出现了一些错误。从你的询问中我了解到我用错了syntax@Viktor . . . 标准SQL不是select distinct。这是选择不同的。
select distinct on (user_id) rh.*
from ratio_history rh
order by user_id, year desc, month desc;