Postgres:如何在按操作结果排序时获取行号?

时间:2016-04-29 09:18:09

标签: sql postgresql row-number

我们假设有一个表'items'有三列:'id','pos'和'neg',选择结果应按操作pos - neg的结果排序。< / p>

所以,以下应该有效:

SELECT
    id,
    pos - neg AS diff
FROM items
ORDER BY diff DESC

现在我需要获取特定行(在表格中)的位置,按“diff”排序结果。我试过这个:

WITH summary AS (
    SELECT
        i.id,
        i.pos - i.neg AS diff,
        ROW_NUMBER() OVER(ORDER BY diff) AS position
    FROM items i)
SELECT s.*  FROM summary s WHERE s.id = 351435254

但执行返回ERROR:列“diff”不存在。

那么,是否可以获得该位置,或者将差异保持在单独的列中会更好?

2 个答案:

答案 0 :(得分:1)

为避免重复计算,只需将ROW_NUMBER()移至外部查询...

WITH summary AS (
    SELECT
        i.id,
        i.pos - i.neg AS diff       
    FROM
        items i
)
SELECT
    s.*,
    ROW_NUMBER() OVER(ORDER BY s.diff) AS position
FROM
    summary s
WHERE
    s.id = 351435254

在内部查询期间,diff的引用范围仅限于 {/ 1}}之前存在的,否则您可以获得循环引用。

到外部查询时,您的新字段SELECT存在,因此可以作为参数提供给其他计算,函数等。

答案 1 :(得分:0)

尝试:

WITH summary AS (
    SELECT
        i.id,
        i.pos - i.neg AS diff,
        ROW_NUMBER() OVER(ORDER BY (i.pos - i.neg)) AS position
    FROM items i)
SELECT s.*  FROM summary s WHERE s.id = 351435254