【问题标题】:Is there a PostgreSQL function that calculates the percentage difference from the first row only?是否有一个 PostgreSQL 函数只计算与第一行的百分比差异?
【发布时间】:2021-05-08 05:06:50
【问题描述】:

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

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

我试图用这样的 lag() 来解决它,但没有找到任何方法来修复 page==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() 像这样工作,或者有一个内置函数可以做到这一点?

【问题讨论】:

    标签: sql postgresql percentage


    【解决方案1】:

    使用first_value 而不是lag

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

    【讨论】:

      猜你喜欢
      • 2020-11-27
      • 2013-10-27
      • 1970-01-01
      • 2021-06-17
      • 2021-01-05
      • 1970-01-01
      • 2020-06-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多