Reputation: 807
I have the following (abstract) sequelize model:
{
startTime: Date,
endTime: Date,
}
Now I want to get the average duration of all existing entities. In SQL I'd model this like SELECT AVG("end_time" - "start_time") FROM "MyTable";
. But I don't know how I can do this with sequelize.
I've made some attempts on using sequelize.fn()
but did not come to a conclusion.
So my goal is to have something like:
MyModel.findAll({
attributes: ['averageTime' <<< now what?]
});
Oh and I'm using PostgreSQL 9.6.
Best, Philipp
Upvotes: 2
Views: 1191
Reputation: 15881
You can't use findAll
or findOne
as they return instance(s) of the model and you need to get some scalar value.
Raw query can be used to do what you need like this:
sequelize.query(
'SELECT AVG("end_time" - "start_time") FROM "MyTable"',
{ type: sequelize.QueryTypes.SELECT}
).then(function(result) {
// process result here
})
Upvotes: 3