在 SQLAlchemy 中使用 alias() 为“select as" [英] Using alias() for 'select as' in SQLAlchemy

查看:74
本文介绍了在 SQLAlchemy 中使用 alias() 为“select as"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个包含以下列的共享"表:

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

我想像这样运行 SQL 语句的等效语句:

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;

离我最近的是:

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

我在 sqlalchemy 中设置总和(数量)为 num"时遇到问题.看来我需要使用 alias() 但我无法通过查看文档来弄清楚如何使用.如果有人能告诉我怎么做,我将不胜感激.

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.

非常感谢!

推荐答案

您实际上想要 label 方法.

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()

这篇关于在 SQLAlchemy 中使用 alias() 为“select as"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆