column label and order by

1,679 views
Skip to first unread message

rajasekhar911

unread,
Nov 14, 2009, 8:48:06 AM11/14/09
to sqlalchemy
Hi guys,

how do i apply order by on a column with a label.
My requirement is like this

class x
id,
amount,
date

i have to group based on id and take sum of amount within a date
range.

i am applying a label to sum of amount
now how do i order based on that so that i can get top 5 ..

session.query( func.sum(x.amount).label('tot_amount'), x.id ).
filter(x.date>fromdate).filter(x.date<todate).
.group_by(x.id)
.order_by(?????)
.limit(5)


thanks.

rajasekhar911

unread,
Nov 17, 2009, 6:32:23 AM11/17/09
to sqlalchemy
anyone??

King Simon-NFHD78

unread,
Nov 17, 2009, 6:38:52 AM11/17/09
to sqlal...@googlegroups.com

How about (untested):

tot_amount = func.sum(x.amount).label('tot_amount')
session.query(tot_amount, x.id).
filter(x.date>fromdate).filter(x.date<todate).
.group_by(x.id)
.order_by(tot_amount)
.limit(5)

Simon

Mike Conley

unread,
Nov 17, 2009, 6:55:52 AM11/17/09
to sqlal...@googlegroups.com
And you do need to quote the column name in order_by also.

session.query(func.sum(X.amount).label('tot_amount')).group_by(X.date).order_by('tot_amount').limit(10)

generates code

SELECT sum(x.amount) AS tot_amount
FROM x GROUP BY x.date ORDER BY tot_amount
 LIMIT 10 OFFSET 0


rajasekhar911

unread,
Nov 17, 2009, 8:16:04 AM11/17/09
to sqlalchemy
session.query( func.sum(x.amount).label('tot_amount'), x.id ).
filter(x.date>fromdate).filter(x.date<todate).
.group_by(x.id)
.order_by('tot_amount DESC')
.limit(5)
Reply all
Reply to author
Forward
0 new messages