简体   繁体   English

如何获取 SQLAlchemy 和 postgresql 数据库中的最后一次出现?

[英]How to get last occurrences in SQLAlchemy and postgresql database?

How to query postgres database to get grouped result with last occurrence?如何查询 postgres 数据库以获取最后一次出现的分组结果?

I have a table like this one:我有一张这样的桌子:

id | emp_id | hours
1  | 1      | 8
2  | 1      | 6
3  | 2      | 6
4  | 2      | 3
5  | 1      | 5

I want to receive below result:我想收到以下结果:

emp_id | hours
1      | 5
2      | 3

I want it to be ordered descending by id and get last value for each employee.我希望它按 id 降序排列并获得每个员工的最后一个值。

You probably want to use some group by and do something like:您可能想使用一些 group by 并执行以下操作:

from sqlalchemy import func
session.query(Table.col_emp_id,func.max(Table.col_hour)).group_by(Table.col_emp_id).all()

I'm not an expert, just a clue我不是专家,只是一个线索

The script below can give you the expected result:下面的脚本可以给你预期的结果:

 select emp_id,hours from ( select *, row_number() over(partition by emp_id order by id desc) as rank from <your_table> )tab where tab.rank=1

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

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