Chrome Extension

Count Rows group by column name SqlAlchemy

Group by in SQLAlchemy can be applied using the group_by() method. In the code example we are trying to get the counts of users according top their roles.
user_counts = session.query(
                UserModel.role, 
                func.count(UserModel.role).label("total_counts")
            ).group_by(
                UserModel.role
            ).all()

#THE ABOVE QUERY CAN OUTPUT DATA:
#  +-------------+----------------+
#  | role        | total_counts   |
#  +-------------+----------------+
#  | Admin       | 100            |
#  | Super Admin | 50             |
#  | user        | 1700           |
#  +-------------+----------------+
Code faster with devsheet chrome extension and increase productivity as a programmer
search code from your favorite search engine instantly.
Install Now

Search Index Data (The code snippet can also be found with below search text)

group_by() SQLAlchemy
Was this helpful?
0 Comments
Open Code Manager We are hiring