在SQLAlchemy中使用alias()作为"select as"

Vis*_*akh 27 python sqlalchemy pyramid

假设我有一个表'shares'与以下列:

company    price    quantity
Microsoft  100      10
Google     99       5
Google     99       20
Google     101      15
Run Code Online (Sandbox Code Playgroud)

我想运行相当于这样的SQL语句:

select price, 
       sum(quantity) as num 
from shares 
where company='Google' 
group by price;
Run Code Online (Sandbox Code Playgroud)

我最接近的是:

result = (dbsession.query(Shares.price, func.sum(Shares.quantity))
         .filter(Shares.company == 'Google')
         .group_by(Shares.price)
         .all())
Run Code Online (Sandbox Code Playgroud)

我在sqlalchemy中设置'sum(quantity)as num'时遇到了麻烦.看来我需要使用别名(),但我无法通过查看文档来弄清楚如何.如果有人能告诉我该怎么做,我将不胜感激.

非常感谢!

Sea*_*ira 79

你真的想要这个label方法.

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

  • 太棒了,这正是我想要的。非常感谢! (2认同)
  • 我们可以在列名上使用`.label`吗?像`query(Shares.type.label("shares_type")).group_by(shares_type)`? (2认同)
  • @夏溪辰 - 最好为此提出一个单独的问题。 (2认同)