python - 使用窗口函数在 Postgres 上使用 SqlAlchemy 限制查询

标签 python sql sqlalchemy

我正在尝试使用 sqlalchemy ORM 编写以下 sql 查询:

SELECT * FROM
   (SELECT *, row_number() OVER(w)
    FROM (select distinct on (grandma_id, author_id) * from contents) as c
    WINDOW w AS (PARTITION BY grandma_id ORDER BY RANDOM())) AS v1
WHERE row_number <= 4;

这是我到目前为止所做的:

s = Session()

unique_users_contents = (s.query(Content).distinct(Content.grandma_id,
                                                  Content.author_id)
                         .subquery())

windowed_contents = (s.query(Content,
                             func.row_number()
                             .over(partition_by=Content.grandma_id,
                                   order_by=func.random()))
                     .select_from(unique_users_contents)).subquery()

contents = (s.query(Content).select_from(windowed_contents)
            .filter(row_number >= 4)) ##  how can I reference the row_number() value?

result = contents
for content in result:
    print "%s\t%s\t%s" % (content.id, content.grandma_id,
                          content.author_id)

如您所见,它几乎是建模的,但我不知道如何从外部查询中引用子查询的 row_number() 结果。我尝试了类似 windowed_contents.c.row_number 的东西,并在窗口函数上添加了一个 label() 调用,但它不起作用,在官方文档中找不到任何类似的例子或在 stackoverflow 中。

如何做到这一点?另外,您能否建议一种更好的方法来执行此查询?

最佳答案

windowed_contents.c.row_number 针对 label() 是你会怎么做,对我有用(注意 select_entity_from() 方法是 SQLA 0.8.2 中的新方法,与 select_from() 相比,0.9 中将需要这里:

from sqlalchemy import *
from sqlalchemy.orm import *
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()

class Content(Base):
    __tablename__ = 'contents'

    grandma_id = Column(Integer, primary_key=True)
    author_id = Column(Integer, primary_key=True)


s = Session()

unique_users_contents = s.query(Content).distinct(
                            Content.grandma_id, Content.author_id).\
                            subquery('c')

q = s.query(
        Content,
        func.row_number().over(
                partition_by=Content.grandma_id,
                order_by=func.random()).label("row_number")
    ).select_entity_from(unique_users_contents).subquery()

q = s.query(Content).select_entity_from(q).filter(q.c.row_number <= 4)

print q

关于python - 使用窗口函数在 Postgres 上使用 SqlAlchemy 限制查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17437317/

相关文章:

python - 如何在 SQLAlchemy ORM 中表达多表更新(UPDATE FROM)?

python - 将图像从 float32 转换为 uint8 时,蒙版对象消失

Python:尝试将 int 转换为列表时,int 对象不可迭代

python - 匹配有效变量模式的正则表达式

python - SQLAlchemy 查询与多列元组上的比较

python - SQLAlchemy 使用现有主键创建新对象

python - 如何将 Pandas 中的非零条目转换为带列表的字典?

mysql - 如何知道SQL中记录的插入日期

Java:从现有表生成 CREATE TABLE 代码

sql - 在DolphinDB中,如何使用ols函数基于表计算股票剩余 yield ?