我有以下 SQL 代码,它返回得分高于特定条目的条目数。
select (select count(*)
from entries e2
where e1.score < e2.score) + 1 as pos
from entries e1
where e1.ID = 36;
我在将它翻译成 Sequelize.js 时遇到了很多麻烦。我有一个解决方案可以在 2 个查询中实现这一点,但我想在单个查询中完成。
this.dal.Entries.getPositionInList = (ID: number) => {
return this.db.Entries.findOne({
where: {
ID: ID
}
}).then((entry: any) => {
return this.db.Entries.findAndCountAll({
where: {
score: {
$gt: entry.score
}
}
});
});
};
最佳答案
您的查询可以通过多种方式表达。也许有一个你可以转换成一些 Sequelize 代码? (我不知道,我只是希望下面的内容有帮助):
SELECT COUNT(*)
FROM entries
WHERE score >= (SELECT score FROM entries WHERE id = 36);
SELECT COUNT(*) OVER (ORDER BY score DESC)
FROM entries
ORDER BY id <> 36
LIMIT 1;
SELECT COUNT(*)
FROM entries s1
LEFT JOIN entries s2 ON s2.score >= s1.score
WHERE s1.id = 36;
关于postgresql - 如何统计分数高于 [userID] 的用户数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41611609/