title: Using group by and joins in sequelize
body: <p>I have two tables on a PostgreSQL database, contracts and payments. One contract has multiple payments done.</p>
  
  <p>I'm having the two following models:</p>
  
  <pre><code> module.exports = function(sequelize, DataTypes) {
    var contracts = sequelize.define('contracts', {
      id: {
        type: DataTypes.INTEGER,
        autoIncrement: true
      }
    }, {
      createdAt: false,
      updatedAt: false,
      classMethods: {
        associate: function(models) {
          contracts.hasMany(models.payments, {
            foreignKey: 'contract_id'
          });
        }
      }
    });
  
  
    return contracts;
  };
  
  module.exports = function(sequelize, DataTypes) {
    var payments = sequelize.define('payments', {
      id: {
        type: DataTypes.INTEGER,
        autoIncrement: true
      },
      contract_id: {
        type: DataTypes.INTEGER,
      },
      payment_amount: DataTypes.INTEGER,
    }, {
      classMethods: {
        associate: function(models) {
          payments.belongsTo(models.contracts, {
            foreignKey: 'contract_id'
          });
        }
      }
    });
  
  
    return payments;
  };
  </code></pre>
  
  <p>I would like to sum all the payments made for every contract, and used this function:</p>
  
  <pre><code>models.contracts.findAll({
      attributes: [
          'id'
      ],
      include: [
      {
          model: models.payments,
          attributes: [[models.sequelize.fn('sum', models.sequelize.col('payments.payment_amount')), 'total_cost']]
      }
      ],
      group: ['contracts.id']
  })
  </code></pre>
  
  <p>But it generates the following query:</p>
  
  <pre><code>SELECT "contracts"."id", "payments"."id" AS "payments.id", sum("payments"."payment_amount") AS "payments.total_cost" 
  FROM "contracts" AS "contracts" 
  LEFT OUTER JOIN "payments" AS "payments" ON "contracts"."id" = "payments"."contract_id" GROUP BY "contracts"."id";
  </code></pre>
  
  <p>I do not ask to select payments.id, because I would have to include it in my aggregation or group by functions, as said in the error I have:</p>
  
  <blockquote>
    <p>Possibly unhandled SequelizeDatabaseError: error: column "payments.id"
    must appear in the GROUP BY clause or be used in an aggregate function</p>
  </blockquote>
  
  <p>Am I missing something here ? I'm following <a href="https://stackoverflow.com/questions/25700004/how-can-i-do-a-group-by-across-3-tables-with-sequelize">this answer</a> but even there I don't understand how the SQL request can be valid.</p>