在一个查询中使用func.max和func.count

时间:2014-03-11 22:59:51

标签: python sql sqlalchemy

我有两张桌子:

class Shops(db.Model):
    id = db.Column(db.Integer, primary_key = True)
    name = db.Column(db.String(255))
    order = db.relationship('Order', backref = 'purchased', lazy = 'dynamic')

class Order(db.Model):
    id = db.Column(db.Integer, primary_key = True)
    date = db.Column(db.DateTime)
    shop = db.Column(db.Integer, ForeignKey('shop.id'))

我想根据订单获得最畅销的商店,如下:

query = db.session.query(Shops.name.label('TopShop'),Order,func.max(func.count(Order.shop)))

出现以下错误:

ProgrammingError: (ProgrammingError) (1111, u'Invalid use of group function') 

请问正确的指示?

1 个答案:

答案 0 :(得分:1)

订单数量

的顶级商店。

subq = (session.query(Order.shop, func.count(Order.id).label("num_orders")).
        group_by(Order.shop)).subquery()
q = session.query(Shops).join(subq, Shops.id == subq.c.shop).order_by(subq.c.num_orders.desc())

# top 1
print q.first()
# top 5
print q[:5]