selecting from a subquery in sqlalchemy

275 views
Skip to first unread message

Jonathan Vanasco

unread,
Dec 11, 2012, 3:41:20 PM12/11/12
to sqlal...@googlegroups.com
does anyone have a good reference for this ?

i'm trying to select 

    Table.Column , count(Table.Column)

however I'm not querying the Table, instead the raw sql is more like

     SELECT a , COUNT(a) FROM ( SELECT FROM TABLE ) AS sq1

i've never had to select from a subquery in sqlalchemy before.  I can't wrap my head around this and I can't find relevant docs 

Audrius Kažukauskas

unread,
Dec 11, 2012, 4:04:05 PM12/11/12
to sqlal...@googlegroups.com
Something like the following should do the trick:

subq = db_session.query(Model1.field1).\
filter(Model1.field2 == 'bar').subquery()
q = db_session.query(subq.c.field1, func.count(subq.c.field1)).\
group_by(subq.c.field1)

You may want to look at
http://docs.sqlalchemy.org/en/rel_0_8/orm/tutorial.html#using-subqueries
for more examples and explanations.

--
Audrius Kažukauskas
http://neutrino.lt/

Jonathan Vanasco

unread,
Dec 11, 2012, 6:45:45 PM12/11/12
to sqlal...@googlegroups.com
ah, it was in the tutorial
thanks so much!
Reply all
Reply to author
Forward
0 new messages