Sql Alchemy将子查询与group by子句相关联

时间:2016-09-10 20:05:58

标签: python mysql sql sqlalchemy correlated-subquery

我有一个表OrderItem,如下所示:

class OrderItem(db.Model):
 linq_order_num = db.Column(GUID, primary_key=True)
 order_status_id = db.Column(db.Integer, db.ForeignKey('order_status.id'))
 order_id = db.Column(db.String(100))
 item_name = db.Column(db.String(120))
 item_cost = db.Column(db.Float)
 custmer_id = db.Column(db.Integer, db.ForeignKey('customer.id'))
 order_date_time = db.Column(db.DateTime, default=datetime.now(india_timezone))
 order_category = db.Column(db.String(120))
 ordered_by = db.Column(db.Integer, db.ForeignKey('user.id'))
 linq_shipping_cost = db.Column(db.Float)
 website_shipping_cost = db.Column(db.Float)
 total_cost = db.Column(db.Float)
 advance_amount = db.Column(db.Float)
 website = db.Column(db.String(120))
 other = db.Column(db.String(120))
 rvn = db.Column(db.Integer)
 received_date = db.Column(db.DateTime)
 delivered_date = db.Column(db.DateTime)
 store_id = db.Column(db.Integer, db.ForeignKey('store.id'))

现在我想找出order_date_time分组的total_cost总和 另外,我想找到按total_date分组的(total_amount - advance amount)的总和。

我可以在单个查询中实现此目的吗? 我正在尝试以下方面:

   payments = db.session.query(func.date_format(OrderItem.order_date_time,'%Y-%m-%d').label('date'), func.sum(OrderItem.total_cost).label('total'), func.sum(OrderItem.advance_amount).label('advance_amount'),(db.session.query( func.sum(OrderItem.total_cost- OrderItem.advance_amount) ).filter(func.date_format(OrderItem.delivered_date,'%Y-%m-%d') == func.date_format(OrderItem.order_date_time,'%Y-%m-%d')).group_by(func.date_format(OrderItem.delivered_date, '%Y-%m-%d')).all())).group_by(func.date_format(OrderItem.order_date_time, '%Y-%m-%d')).all()

但它不起作用。我相信这是一个带有分组子句的相关子查询。任何线索都会非常有帮助。

0 个答案:

没有答案