Simple example of a GROUP BY

3,610 views
Skip to first unread message

Andrew Bialecki

unread,
Jul 5, 2010, 11:55:08 PM7/5/10
to sqlalchemy
I've looked for a while, but I can't find the *best* way to use the
ORM to generate the following query:

SELECT user_id, count(*) cnt
FROM orders
GROUP BY user_id

I have classes that represent both User and Order. So what should go
after:

Order.query.[fill this in]

Sorry this is such an easy question, feel free to forward me to an
example, I just couldn't find one.

Lance Edgar

unread,
Jul 6, 2010, 12:24:10 AM7/6/10
to sqlal...@googlegroups.com

I think the following might work?


from sqlalchemy import func

session.query(Order.user_id,
func.count(Order.user_id)).group_by(Order.user_id)


Anyway a little more is to be found here:

http://www.sqlalchemy.org/docs/ormtutorial.html#counting
http://www.sqlalchemy.org/docs/reference/orm/query.html#sqlalchemy.orm.query.Query.group_by

Lance

Reply all
Reply to author
Forward
0 new messages