I want a “group by and count” command in sqlalchemy. How can I do this?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
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()
Method 2
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()
Method 3
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.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0