Group by & count function in sqlalchemy

I need the "group by and count" command in sqlalchemy. How can i do this?

+78
python count group-by sqlalchemy
Jun 27 '09 at 5:10
source share
3 answers

The documentation during the count says that for group_by queries group_by better to use func.count() :

 from sqlalchemy import func session.query(Table.column, func.count(Table.column)).group_by(Table.column).all() 
+132
Nov 03 '10 at 10:44
source share

You can also count on several groups and their intersection:

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

In the above query, the counts will be returned for all possible combinations of values ​​from both columns.

+26
Mar 11 '11 at 17:10
source share

If you use the Table.query property:

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

If you use the session.query() method (as indicated in the miniwark answer):

 from sqlalchemy import func session.query(Table.column, func.count(Table.column)).group_by(Table.column).all() 
+16
Jul 05 '18 at 13:58
source share



All Articles