title: GroupBy and Sum in SQLAlchemy?
body: <p>I am trying to group a few fields in a table, and then sum the groups, but they are getting double counted.  </p>
  
  <p>My models are as follows:</p>
  
  <pre><code>class CostCenter(db.Model):
       __tablename__ = 'costcenter'
       id = db.Column(db.Integer, primary_key=True, autoincrement=True)
       name = db.Column(db.String)
       number = db.Column(db.Integer)
  
  class Expense(db.Model):
  
      __tablename__ = 'expense'
      id = db.Column(db.Integer, primary_key=True, autoincrement=True)
      glitem_id = db.Column(db.Integer, db.ForeignKey('glitem.id'))
      glitem = db.relationship('GlItem')
      costcenter_id = db.Column(db.Integer, db.ForeignKey('costcenter.id'))
      costcenter = db.relationship('CostCenter')
      value = db.Column(db.Float)
      date = db.Column(db.Date)
  </code></pre>
  
  <p>I have been using:</p>
  
  <pre><code>expenses=db.session.query(Expense,func.sum(Expense.value)).group_by(Expense.date).filter(CostCenter.id.in_([1,2,3]))
  </code></pre>
  
  <p>When I print expenses it shows the SQL statement that follows. It looks correct to me, but I am not that familiar with SQL. The problem is that the values it outputs as sum_1 are being counted multiple times.  If I have [1] item in the "in statment" it will sum all three.  If I have [1,2], it will sum all three and then double it, and if i have [1,2,3], it will sum all three and triple it.  I am not sure why it is counting multiple times.  How do I fix this?    </p>
  
  <pre><code>SELECT expense.id AS expense_id, expense.glitem_id AS expense_glitem_id, expense.costcenter_id AS         expense_costcenter_id, expense.value AS expense_value, expense.date AS expense_date, sum(expense.value) AS sum_1 
  FROM expense, costcenter 
  WHERE costcenter.id IN (:id_1, :id_2, :id_3) GROUP BY expense.date
  </code></pre>
  
  <p>Thanks!</p>