简体   繁体   English

如何获取每个user_id的最后一个值(postgreSQL)

[英]How to get last value for each user_id (postgreSQL)

Current ratio of user is his last inserted ratio in table "Ratio History" 用户的当前比率是他在“比率历史记录”表中最后插入的比率

user_id | year | month | ratio

For example if user with ID 1 has two rows 例如,如果ID为1的用户有两行

1 | 2019 | 2 | 10
1 | 2019 | 3 | 15

his ratio is 15. 他的比率是15

there is some slice from develop table 从开发表中切出一些

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

I need a query which will select grouped rows by user_id and their last ratio. 我需要一个查询,它将按user_id及其最后的比率选择分组的行。

As a result of the request, the following entries should be selected 根据请求,应选择以下条目

user_id | year | month | ratio
    1 | 2019 | 1 | 40
    2 | 2019 | 3 | 70
    3 | 2018 | 10 | 60

I tried use this query 我尝试使用此查询

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

but i got only one row 但我只有一排

Use distinct on : distinct on以下使用不distinct on

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

distinct on is a very convenient Postgres extension. distinct on是非常方便的Postgres扩展。 It returns one row for the key values in parentheses? 它返回括号中的键值的一行吗? Which row, it is the first row based on the sort criteria. 哪一行是基于排序标准的第一行。 Note that the sort criteria need to start with the expressions in parentheses. 请注意,排序条件需要以括号中的表达式开头。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM