gpt4 book ai didi

python - SQLAlchemy 中的总计分组

转载 作者:太空宇宙 更新时间:2023-11-03 15:25:24 24 4
gpt4 key购买 nike

我似乎找不到关于此的任何好的文档。我有一个用户和订单金额列表,我想显示订单金额总计前 10 名的用户。我在创建查询以充分提取 SQLAlchemy 中的这些数据时遇到了问题。有没有更好的方法来解决这个问题?

customers, amount = DBSession.query(Order.customer, func.sum(Order.amount).label('totalamount')).\
group_by(Order.customer).\
order_by(func.desc(totalamount)).\
limit(10)

for a, b in zip(customers, amount):
print a.name, str(amount)

最佳答案

from sqlalchemy import *
from sqlalchemy.orm import *
from sqlalchemy.ext.declarative import declarative_base
import random

Base= declarative_base()

class Customer(Base):
__tablename__ = 'customer'
id = Column(Integer, primary_key=True)
name = Column(Unicode)
orders = relationship("Order", backref="customer")

class Order(Base):
__tablename__ = "order"

id = Column(Integer, primary_key=True)
customer_id= Column(Integer, ForeignKey('customer.id'))
amount = Column(Integer)

e = create_engine("sqlite://", echo=True)
Base.metadata.create_all(e)

session = Session(e)

session.add_all([
Customer(name="c%d" % i, orders=[
Order(amount=random.randint(10, 100))
for j in xrange(random.randint(0, 5))
])
for i in xrange(100)
])

amount_sum = func.sum(Order.amount).label('totalamount')
amount = session.query(Order.customer_id, amount_sum).\
group_by(Order.customer_id).\
order_by(amount_sum.desc()).\
limit(10).\
subquery()

for a, b in session.query(Customer, amount.c.totalamount).\
join(amount, amount.c.customer_id==Customer.id):
print a.name, b

关于此处模式的一些指南位于 http://www.sqlalchemy.org/docs/orm/tutorial.html#using-subqueries , 但总体上首先从 SQL 开始。

关于python - SQLAlchemy 中的总计分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7882129/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com