使用PostgreSQL聚合ORDER BY和sqlalchemy

时间:2013-01-29 14:27:45

标签: python postgresql sqlalchemy

我有一个查询,它使用PostgreSQL的语法在聚合函数中使用ORDER BY,如下所示:

SELECT some_agg_func(a ORDER BY b DESC) FROM table;

有没有人知道用sqlalchemy表达式语言来做这件事?

3 个答案:

答案 0 :(得分:6)

我认为SqlAlchemy 1.1现在支持string_agghttp://docs.sqlalchemy.org/en/latest/dialects/postgresql.html#sqlalchemy.dialects.postgresql.aggregate_order_by(在页面中搜索“func.string_agg”)

答案 1 :(得分:1)

您需要使用SQLAlchemy的compiler扩展来实现此目的。以下是Postgres string_agg函数的示例:

from sqlalchemy.sql.expression import ColumnElement, _literal_as_column
from sqlalchemy.dialects import postgresql
from sqlalchemy.ext.compiler import compiles

class string_agg(ColumnElement):
    def __init__(self, expr, separator, order_by=None):
        self.type = Text()
        self.expr = _literal_as_column(expr)
        self.separator = literal(separator)
        self.order_by = _literal_as_column(order_by)

    @property
    def _from_objects(self):
        return self.expr._from_objects

@compiles(string_agg, 'postgresql')
def compile_string_agg(element, compiler, **kwargs):
    head = 'string_agg(%s, %s' % (
        compiler.process(element.expr),
        compiler.process(element.separator)
    )
    if element.order_by is not None:
        tail = ' ORDER BY %s)' % compiler.process(element.order_by)
    else:
        tail = ')'
    return head + tail

query = session.query(string_agg(Foo.bar, ', ', order_by=Foo.bar.desc()))
# Print compiled SQL query.
print query.statement.compile(dialect=postgresql.dialect())
# Run the query and print result.
print query.scalar()

答案 2 :(得分:0)

SQLAlchemy Docs

from sqlalchemy.dialects.postgresql import aggregate_order_by

expr = func.array_agg(aggregate_order_by(table.c.a, table.c.b.desc()))
stmt = select([expr])