Group by & count function in sqlalchemy

PythonGroup ByCountSqlalchemy

Python Problem Overview


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

Python Solutions


Solution 1 - Python

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()

Solution 2 - Python

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()

Solution 3 - Python

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionNazmul HasanView Question on Stackoverflow
Solution 1 - PythonminiwarkView Answer on Stackoverflow
Solution 2 - PythonJakub KukulView Answer on Stackoverflow
Solution 3 - PythonfccoelhoView Answer on Stackoverflow