Using Sequelize ORM for Node.js, how do you use CASE/WHEN expression in a select statement?
I do not see any reference or examples to use the SQL expression CASE acc
You can use Sequelize.literal in attributes
to build special queries
var query = {
attributes: [
'userId',
[Sequelize.literal(`MAX(CASE Type WHEN 'Employee' THEN Rate ELSE 0 END)`), 'Employee'],
[Sequelize.literal(`MAX(CASE Type WHEN 'School' THEN Rate ELSE 0 END)`), 'School'],
[Sequelize.literal(`MAX(CASE Type WHEN 'Public' THEN Rate ELSE 0 END)`), 'Public'],
[Sequelize.literal(`MAX(CASE Type WHEN 'Other' THEN Rate ELSE 0 END)`), 'Other'],
],
where: {
user: userId,
Type: ['Employee', 'School', 'Public', 'Other'],
},
group: ['userId'],
raw: true
};
models.invoice.findAll(query).then(result => {
console.log(result);
});