Search code examples
sqlnode.jspostgresqlsumsequelize.js

How can I use sum of columns in where in postgres sequelize


I have problem in my query I have query to get result with sum of one column :

const { Op, literal, fn, col } = this.app.Sequelize;

const timeTableWhere = {
  [Op.and]: [
    {
      durationTimestamp: {
        [Op.gte]: hourTimestamp,
      },
    },
  ],
};
const timetables = await ctx.model.Timetable.findAll({
  attributes: [
    'userId',
    'dow',
    'type',
    [fn('SUM', col('duration_timestamp')), 'durationTimestamp'],
  ],
  where: timeTableWhere,
  group: ['dow', 'userId', 'type'],
});

Now I want check hourTimestamp with sum of duration_timestamp column in my where but my condition just check value of one column. thanks


Solution

  • hey I resolved this problem with add having in my query like this :

    const { Op, literal, fn, col ,where} = this.app.Sequelize;
        const timetables = await ctx.model.Timetable.findAll({
          attributes: [
            'userId',
            'dow',
            'type',
            [fn('SUM', col('duration_timestamp')), 'durationTimestamp'],
          ],
          having:{
             [Op.and]: [
               where(fn('SUM', col('duration_timestamp')) , { [Op.gte]: hourTimestamp,})
                       ],
                 },
          group: ['dow', 'userId', 'type'],
        });