如何在模型上运行 RANK() 函数



如何运行排名函数以在给定的续集模型上生成属性?

例如,给定模型:

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

我想在运行Players.getAll({ rank: rating })时获得一个属性rank.这将生成类似于以下内容的 SQL:

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

我将如何使用续集来做到这一点?

你可以像下面这样使用 Sequelize Literal 函数 -

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

以创建新属性。

最新更新