SQLAlchemy 查找最后一列值,其中存在另一列的所有值

SQLAlchemy find last column values where all values of another column exist

所以这可能是一个简单的问题,但给出的 table 看起来像

A    |  B   |  C
2020 | 1    | apple
2020 | 1    | pear
2020 | 1    | banana
2020 | 2    | apple
2020 | 2    | pear
2020 | 3    | apple
2020 | 3    | banana

我想要最后一个 A, B 组合,它在 C

中同时具有 applepear

如何在 sqlalchemy 中使用命令 s.t。它将 return (2020, 2)

所以我有

from sqlalchemy import func
from sqlalchemy.sql import desc


result = session.\
    query(table.A, table.B).\
    order_by(desc(table.A)).\
    order_by(desc(table.B)).\
    groupby(table.A, table.B).\
    having(func.count() == 2).\
    first()

但我需要 having 的逻辑来解析列 C 并找到第一个同时具有 applepear

的人

哇抱歉,我很快就想通了

from sqlalchemy import func
from sqlalchemy.sql import desc

c_list = ['apple', 'pear']

result = session.\
    query(table.A, table.B).\
    filter(table.C.in_(c_list)).\
    order_by(desc(table.A)).\
    order_by(desc(table.B)).\
    groupby(table.A, table.B).\
    having(func.count() == len(c_list)).\
    first()

唯一的问题是,这假设 A、B 和 C 的所有组合都是不同的。不确定如何解决这个问题...

如果 3 列之间没有唯一性(例如,可以有 2 行带有 (2020, 2, 'pear')),下面仍将提供适用于任何标准数量:

c_list = ["apple", "pear"]
subq_list = [
    session.query(table.A, table.B)
    .filter(table.C == c_item)
    .distinct()
    .subquery()
    for c_item in c_list
]

# compose the query from the parts
s1, *s_rest = subq_list
stmt = select(s1).order_by(s1.c.A.desc(), s1.c.B.desc()).limit(1)
for s2 in s_rest:
    stmt = stmt.join(s2, and_(s1.c.A == s2.c.A, s1.c.B == s2.c.B))

for x in session.execute(stmt):
    print(x)