postgresql 获取上次实际数据

oprakyz7  于 2023-04-11  发布在  PostgreSQL
关注(0)|答案(1)|浏览(169)

有一个表rule_chains
| ID|工资单类型标识|员工部门ID|开始日期|
| --------------|--------------|--------------|--------------|
| 1|1|八九|2023-03-01 2023-03-01 2023-03-01|
| 二|二|八九|2023-03-01 2023-03-01 2023-03-01|
| 三|1|八九|2023-04-01 2023-04-01|
我的问题是获取今天的实际实体。例如今天是2023-03-01,我需要获取这两个实体,id = 1和id = 2。但如果今天是2023-04-01,我需要获取id = 2和id = 3。因为payroll_type_id = 1的今天的实际rule_chain是实体,id = 3。
我试着用sqlalchemy写代码,像这样,但它不工作。

subquery = self.session.query(func.min(RuleChain.start_date).label("start_date"),
                                          RuleChain.stuff_department_id,
                                           RuleChain.payroll_type_id).group_by(
     RuleChain.stuff_department_id, RuleChain.payroll_type_id).having(
     func.max(RuleChain.start_date) >= self.date).subquery()

 rule_chains: List[RuleChain] = self.session.query(RuleChain).filter(
     subquery.c.start_date == RuleChain.start_date,
     subquery.c.stuff_department_id == RuleChain.stuff_department_id,
     subquery.c.payroll_type_id == RuleChain.payroll_type_id
 ).all()

也许如果你知道任何原始SQL或SQLAlchemy查询,将是很好的。

vxf3dgd4

vxf3dgd41#

试试这个:

from sqlalchemy import func, and_

# Create a subquery to find the maximum start_date for each group
subquery = (
    self.session.query(
        RuleChain.stuff_department_id,
        RuleChain.payroll_type_id,
        func.max(RuleChain.start_date).label("max_start_date"),
    )
    .filter(RuleChain.start_date <= self.date)
    .group_by(RuleChain.stuff_department_id, RuleChain.payroll_type_id)
    .subquery()
)

# Join the subquery with the main table to get the actual entities for today
rule_chains: List[RuleChain] = (
    self.session.query(RuleChain)
    .join(
        subquery,
        and_(
            RuleChain.stuff_department_id == subquery.c.stuff_department_id,
            RuleChain.payroll_type_id == subquery.c.payroll_type_id,
            RuleChain.start_date == subquery.c.max_start_date,
        ),
    )
    .all()
)

希望能成功。。

相关问题