gpt4 book ai didi

sql - Postgres : How to get row number when ordered by the result of operation?

转载 作者:行者123 更新时间:2023-11-29 13:24:05 24 4
gpt4 key购买 nike

假设有一个表'items',它有三个列:'id'、'pos'和'neg',选择的结果应该按照操作的结果排序pos - neg.

因此,以下应该有效:

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

现在我需要获取特定行(在表中)的位置,并通过“差异”对结果进行排序。我试过这个:

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

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

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

最佳答案

为避免重复计算,只需将 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 的引用将被限制在SELECT 之前 存在的范围内,否则您会得到循环引用。

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

关于sql - Postgres : How to get row number when ordered by the result of operation?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36934390/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com