How to Use Alias in ORDER BY Caluse?

2,316 views
Skip to first unread message

Ji Zhang

unread,
Jan 7, 2013, 9:19:34 PM1/7/13
to sqlal...@googlegroups.com
Hi,

My SQL is like "select host, count(*) as cnt from tbl group by host order by cnt desc"

How to achieve this using ORM?

session.query(Tbl.host, func.count('*').label('cnt')).group_by(Tbl.host).order_by(???)

I don't wanna type again func.count... in order_by().

Thanks.

Michael Bayer

unread,
Jan 7, 2013, 10:28:34 PM1/7/13
to sqlal...@googlegroups.com
count = func.count('*').label('cnt')

query(Tbl.host, count).group_by(Tbl.host).order_by(count.desc())

or

query(Tbl.host, func.count('*').label('cnt').group_by(Tbl.host).order_by(desc('cnt'))


Ji Zhang

unread,
Jan 7, 2013, 11:02:19 PM1/7/13
to sqlal...@googlegroups.com
The second one is neat. Thanks~
Reply all
Reply to author
Forward
0 new messages