How to use CASE WHEN expression in Sequelize?

后端 未结 1 957
轻奢々
轻奢々 2020-12-11 06:02

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

相关标签:
1条回答
  • 2020-12-11 06:46

    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);
    });
    
    0 讨论(0)
提交回复
热议问题