是否有一个 PostgreSQL 函数只计算与第一行的百分比差异?

Is there a PostgreSQL function that calculates the percentage difference from the first row only?

我正在寻找像 PERCENT_RANK() 或 CUME_DIST() 或类似于 lag() 的 PostgreSQL 函数,它只取第一行并计算每个数字的百分比第一个数字。像这样:

page number percentage
0 7347618 100.00%
1 6872759 93.54%
2 5702997 77.62%
3 4914545 66.89%
4 4702129 64.00%

我试图像这样用 lag() 来解决它,但没有找到任何方法来修复页面==0。

select
page,
number as page_impressions,
number::DECIMAL/lag(number)
over(partition by page=0)
from my_table
group by page
order by page

有没有办法让 lag() 像这样工作,或者有内置函数吗?

使用 first_value 而不是 lag

SELECT "page", "number"
     , round(100 * "number"::numeric /
             first_value("number") OVER (ORDER BY "page")
             , 2) AS percentage
FROM my_table