sqlalchemy中的分组和计数功能

问题:sqlalchemy中的分组和计数功能

我想在sqlalchemy中使用“分组并计数”命令。我怎样才能做到这一点?

I want a “group by and count” command in sqlalchemy. How can I do this?


回答 0

关于计数文档说,对于group_by查询,最好使用func.count()

from sqlalchemy import func
session.query(Table.column, func.count(Table.column)).group_by(Table.column).all()

The documentation on counting says that for group_by queries it is better to use func.count():

from sqlalchemy import func
session.query(Table.column, func.count(Table.column)).group_by(Table.column).all()

回答 1

如果您使用Table.query属性:

from sqlalchemy import func
Table.query.with_entities(Table.column, func.count(Table.column)).group_by(Table.column).all()

如果您使用session.query()方法(如miniwark的回答所述):

from sqlalchemy import func
session.query(Table.column, func.count(Table.column)).group_by(Table.column).all()

If you are using Table.query property:

from sqlalchemy import func
Table.query.with_entities(Table.column, func.count(Table.column)).group_by(Table.column).all()

If you are using session.query() method (as stated in miniwark’s answer):

from sqlalchemy import func
session.query(Table.column, func.count(Table.column)).group_by(Table.column).all()

回答 2

您还可以依靠多个组及其交集:

self.session.query(func.count(Table.column1),Table.column1, Table.column2).group_by(Table.column1, Table.column2).all()

上面的查询将返回两列中所有可能的值组合的计数。

You can also count on multiple groups and their intersection:

self.session.query(func.count(Table.column1),Table.column1, Table.column2).group_by(Table.column1, Table.column2).all()

The query above will return counts for all possible combinations of values from both columns.