Postgres排名为专栏

时间:2011-10-14 21:27:48

标签: ruby-on-rails ruby postgresql

我有以下查询:

SELECT name, rank() OVER (PARTITION BY user_id ORDER BY love_count DESC) AS position FROM items

我现在想在rank()函数上做一个where子句:

SELECT name, rank() OVER (PARTITION BY user_id ORDER BY love_count DESC) AS position FROM items WHERE position = 1

也就是说,我想查询每个用户最喜欢的项目。但是,这导致:

PGError: ERROR: column "position" does not exist

另外,我正在使用Rails AREL执行此操作并希望启用链接。这是创建查询的Ruby代码:

Item.select("name, rank() OVER (PARTITION BY user_id ORDER BY love_count DESC) AS position").where("position = 1")

有什么想法吗?

2 个答案:

答案 0 :(得分:6)

您需要将其“包装”到派生表中:

SELECT * 
FROM (
    SELECT name, 
           rank() OVER (PARTITION BY user_id ORDER BY love_count DESC) AS position 
    FROM items
) t
WHERE position = 1

答案 1 :(得分:5)

我的第一个想法是,“使用公共表格表达式”,就像这个未经测试的表达式一样。

WITH badly_named_cte AS (
  SELECT name, 
         rank() OVER (PARTITION BY user_id 
                      ORDER BY love_count DESC) AS position 
  FROM items
)
SELECT * FROM badly_named_cte WHERE position = 1;

您遇到的问题与SQL标准所要求的逻辑评估顺序有关。在评估WHERE子句之后的之前,SQL必须表现为列别名(AS运算符的参数)不存在。