带有Rails的Postgres窗口函数列。

时间:2022-09-27 23:00:20

I'd like to use the rank() function PostgreSQL on one of my columns.

我想在我的一列上使用rank()函数PostgreSQL。

Character.select("*, rank() OVER (ORDER BY points DESC)")

But since I don't have a rank column in my table rails doesn't include it with the query. What would be the correct way to get the rank included in my ActiveRecord object?

但是由于我的表中没有rank列,所以rails不将它包含在查询中。在我的ActiveRecord对象中包含秩的正确方法是什么?

1 个解决方案

#1


3  

try this:

试试这个:

Character.find_by_sql("SELECT *, rank() OVER (ORDER BY points DESC) FROM characters")

it should return you Character objects with a rank attribute, as documented here. However, this may not be database-agnostic and tends to get messy if you pass around the objects.

它应该返回带有rank属性的字符对象,如这里所示。然而,这可能与数据库无关,并且如果您在对象周围传递,会变得很混乱。

another (expensive) solution is to add a rank column to your table, and have a callback recalculate all records' rank using .order whenever a record is saved or destroyed.

另一种(昂贵的)解决方案是向表中添加rank列,并在保存或销毁记录时使用.order重新计算所有记录的秩。

edit :

编辑:

another idea suitable for single-record queries can ben seen here

另一个适合单记录查询的想法可以在这里看到

#1


3  

try this:

试试这个:

Character.find_by_sql("SELECT *, rank() OVER (ORDER BY points DESC) FROM characters")

it should return you Character objects with a rank attribute, as documented here. However, this may not be database-agnostic and tends to get messy if you pass around the objects.

它应该返回带有rank属性的字符对象,如这里所示。然而,这可能与数据库无关,并且如果您在对象周围传递,会变得很混乱。

another (expensive) solution is to add a rank column to your table, and have a callback recalculate all records' rank using .order whenever a record is saved or destroyed.

另一种(昂贵的)解决方案是向表中添加rank列,并在保存或销毁记录时使用.order重新计算所有记录的秩。

edit :

编辑:

another idea suitable for single-record queries can ben seen here

另一个适合单记录查询的想法可以在这里看到