I'm trying to filter results by a function and then also order the resultset with the function column. Here is my code so far:
db.trip.findAll({
attributes: [
[
db.sequelize.fn('SUM',
db.sequelize.col('departure_time'),
db.sequelize.col('arrival_time')),
'summation'
]
],
where: {
summation: {
gte: 500
}
},
order: [['summation', 'ASC']],
logging: console.log
}).then(function(results) {
});
The SQL that gets generated makes it hard to re-reference the alias that gets created in the attributes:
SELECT SUM("departure_time", "arrival_time") AS "summation"
FROM "trip" AS "trip"
WHERE "trip"."summation" >= 500
ORDER BY "trip"."summation" ASC;
Any ideas on how to make this work without making the whole query literal?
I found a way by making a literal statement act as an alias. I'm using Postgres, so I'm not sure if the quoting works in other dialects:
var summationAlias = db.sequelize.literal('"summation"');
db.trip.findAll({
attributes: [
[
db.sequelize.fn('SUM',
db.sequelize.col('departure_time'),
db.sequelize.col('arrival_time')),
'summation'
]
],
where: db.sequelize.where(summationAlias, '>=', 500),
order: [[summationAlias, 'ASC']],
logging: console.log
}).then(function(results) {
});
The above code generates the following SQL:
SELECT SUM("departure_time", "arrival_time") AS "summation"
FROM "trip" AS "trip"
WHERE "summation" >= 500
ORDER BY "summation" ASC;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.