1
计数鉴于这些SQLAlchemy的模型定义:子查询与SQLAlchemy的
class Store(db.Model):
__tablename__ = 'store'
id = Column(Integer, primary_key=True)
name = Column(String, nullable=False)
class CustomerAccount(db.Model, AccountMixin):
__tablename__ = 'customer_account'
id = Column(Integer, primary_key=True)
plan_id = Column(Integer, ForeignKey('plan.id'), index=True, nullable=False)
store = relationship('Store', backref='account', uselist=False)
plan = relationship('Plan', backref='accounts', uselist=False)
class Plan(db.Model):
__tablename__ = 'plan'
id = Column(Integer, primary_key=True)
store_id = Column(Integer, ForeignKey('store.id'), index=True)
name = Column(String, nullable=False)
subscription_amount = Column(Numeric, nullable=False)
num_of_payments = Column(Integer, nullable=False)
store = relationship('Store', backref='plans')
如何编写一个查询的计划,让订阅收入的明细? 我想找回给定商店的计划清单,并为每个计划计算该计划的总收入,计算方法是将Plan.subscription_amount * Plan.num_of_payments *订阅该计划的客户数量相乘计算得出
目前,我试图与此查询和子查询:
store = db.session.query(Store).get(1)
subscriber_counts = db.session.query(func.count(CustomerAccount.id)).as_scalar()
q = db.session.query(CustomerAccount.plan_id, func.sum(subscriber_counts * Plan.subscription_amount * Plan.num_of_payments))\
.outerjoin(Plan)\
.group_by(CustomerAccount.plan_id)
问题是子查询不能在当前计划的ID过滤。
我也试图与该另一种方法(无子查询):
q = db.session.query(CustomerAccount.plan_id, func.count(CustomerAccount.plan_id) * Plan.subscription_amount * Plan.num_of_payments)\
.outerjoin(Plan)\
.group_by(CustomerAccount.plan_id, Plan.subscription_amount, Plan.num_of_payments)
虽然结果似乎很好,我不知道如何回到计划名称或其他计划列,如我d需要通过(并改变结果)将它们添加到组中。
理想情况下,如果一个计划没有任何订阅者,我希望它返回总数为零。
谢谢!