使用 alias() 来“选择为”在 SQLAlchemy 中
假设我有一个包含以下列的表“shares”:
company price quantity
Microsoft 100 10
Google 99 5
Google 99 20
Google 101 15
我想运行相当于这样的 SQL 语句:
select price,
sum(quantity) as num
from shares
where company='Google'
group by price;
我得到的最接近的是:
result = (dbsession.query(Shares.price, func.sum(Shares.quantity))
.filter(Shares.company == 'Google')
.group_by(Shares.price)
.all())
我在设置 'sum(quantity) 时遇到问题) 作为 sqlalchemy 中的 num'。看来我需要使用 alias() 但我无法通过查看文档来弄清楚如何使用。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您实际上想要
标签
方法。You actually want the
label
method.