在SQLAlchemy中对总计进行分组

时间:2011-10-24 21:20:28

标签: python sqlalchemy pyramid

我似乎无法找到任何关于此的好文档。我有一个用户和订单金额列表,我想显示前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)

1 个答案:

答案 0 :(得分:4)

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开始。