5

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

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

有谁知道用 sqlalchemy 表达式语言来做到这一点?

4

3 回答 3

6

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

于 2016-07-05T17:45:17.953 回答
5

SQLAlchemy 文档

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])
于 2018-12-05T16:21:46.870 回答
1

您需要使用 SQLAlchemy 的编译器扩展来实现这一点。string_agg这是 Postgres函数的示例:

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()
于 2013-01-29T16:15:42.233 回答