Home  >  Q&A  >  body text

Using SQLAlchemy’s grouping and counting functions

I want the "Group by and Count" command in sqlalchemy. How can I do this?

P粉031492081P粉031492081370 days ago529

reply all(2)I'll reply

  • P粉180844619

    P粉1808446192023-10-16 09:16:22

    If you use Table.query properties:

    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 described in miniwark's answer):

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

    reply
    0
  • P粉070918777

    P粉0709187772023-10-16 00:27:11

    Count document indicates that for group_by< /code> queries it is best to use func.count():

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

    reply
    0
  • Cancelreply