Using alias() for 'select as' in SQLAlchemy

|▌冷眼眸甩不掉的悲伤 提交于 2019-11-27 03:44:44

问题


Let's say I have a table 'shares' with the following columns:

company    price    quantity
Microsoft  100      10
Google     99       5
Google     99       20
Google     101      15

I'd like to run the equivalent of a SQL statement like this:

select price, 
       sum(quantity) as num 
from shares 
where company='Google' 
group by price;

The closest I've come is:

result = (dbsession.query(Shares.price, func.sum(Shares.quantity))
         .filter(Shares.company == 'Google')
         .group_by(Shares.price)
         .all())

I'm having trouble with setting up the 'sum(quantity) as num' in sqlalchemy. It appears I need to use alias() but I can't figure out how by looking at the documentation. I'd be grateful if someone could show me how to do it.

Many thanks!


回答1:


You actually want the label method.

result = dbsession.query(Shares.price, \
                            func.sum(Shares.quantity).label("Total sold")) \
                            .filter(Shares.company== 'Google') \
                            .group_by(Shares.price).all()


来源:https://stackoverflow.com/questions/9187530/using-alias-for-select-as-in-sqlalchemy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!