How to write a count like this in Sequelize?

Issue

SELECT COUNT(id), age FROM `red_cross_volunteers` GROUP BY age;

Solution

Simply use Sequelize.fn in attributes option and group option while calling findAll:

const stats = await RedCrossVolunteers.findAll({
  attributes: [[Sequelize.fn('COUNT', Sequelize.col('id')), 'age_count'], 'age'],
  group: ['age']
})

Answered By – Anatoly

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published