Mark Thë Brouch
Mark Thë Brouch

Reputation: 189

How to run a RANK() function on a model

How can I run a rank function to generate an attribute on a given sequelize model?

For example, given the model:

Players.init(
  {
    id: {
      type: DataTypes.INTEGER,
      primaryKey: true,
      allowNull: false
    },
    rating: type: DataTypes.FLOAT
  },
  { sequelize }
)

I would like to get an attribute rank when running Players.getAll({ rank: rating }). This would generate SQL similar to:

SELECT id, rating, RANK() OVER (ORDER BY rating DESC) as rank FROM players

How would I do this using sequelize?

Upvotes: 2

Views: 2039

Answers (1)

Rohit Dalal
Rohit Dalal

Reputation: 866

You can use Sequelize Literal Function like follows -

attributes: [
          'id', 'rating',
          [Sequelize.literal('(RANK() OVER (ORDER BY rating DESC))'), 'rank']
    ]

to create new attributes.

Upvotes: 5

Related Questions