Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I express a JOIN and GROUP BY query in SQLAlchemy?

SELECT sector.sector, count(*) 
FROM reports, organization, sector 
WHERE reports.org_id = organization.id
    AND organization.id = sector.org_id
GROUP BY sector.sector;

I'm honestly not even sure where to begin expressing this GROUP BY and JOIN in sqlalchemy.

like image 800
meunierd Avatar asked Feb 01 '26 19:02

meunierd


1 Answers

db.query(func.count(Sector.sector), Sector.sector).\
    join(Organzation).join(Report).\
    group_by(Sector.sector).all()

I was able to represent it as the following expression. My earlier efforts were failing because I needed to db.rollback() my awkward failed attempts.

like image 173
meunierd Avatar answered Feb 03 '26 09:02

meunierd