在PostgreSQL 8.3中实现总订单排名 [英] Implementing a total order ranking in PostgreSQL 8.3
问题描述
8.3的问题是..... rank在8.4中引入。
The issue with 8.3 is.....rank is introduced in 8.4.
考虑数字[10,6,6,2]
consider the numbers [10,6,6,2]
我希望获得这些排名排名等于行号的数字
I wish to achieve a rank of those numbers where the rank is equal to the the row number
Rank,score
1, 10
2,6
3,6
4,2
部分解决方案是自我加入并计算具有更高或更高值的项目等于分数。
A partial solution is to self join and count items with a higher or equal, score.
这会产生
1,10
3,6
3,6
4,2
这不是我想要的。
有没有一种方法可以排名,甚至只是按分数排序,然后以某种方式提取行号?
Is there a way to rank, or even just order by score then somehow extract the row number?
推荐答案
如果要与行号 = nofollow>窗口函数row_number(),您可以在版本8.3中临时使用 SEQUENCE
:
If you want a row number equivalent to the window function row_number(), you can improvise in version 8.3 with a (temporary) SEQUENCE
:
CREATE TEMP SEQUENCE foo;
SELECT nextval('foo') AS rn, *
FROM (SELECT score FROM tbl ORDER BY score DESC) s
SQL Fiddle。
调用 nextval()
之前,必须在子查询中对之前的行进行排序。
SQL Fiddle.
The subselect is necessary to order rows before calling nextval()
.
请注意,序列(像任何临时对象一样)...
Note that the sequence (like any temporary object) ...
- 仅可见在同一会话中创建它。
- 隐藏任何其他同名的表对象。
- 在会话结束时自动删除。
要在同一会话中使用序列,请在每次查询之前重复运行:
To use the sequence in the same session repeatedly run before each query:
SELECT setval('foo', 1, FALSE);
这篇关于在PostgreSQL 8.3中实现总订单排名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!