获取 PostgreSQL 列中选定数据之间的百分比变化

Getting percentage change between selected data within a column in PostgreSQL

我正在使用 PostgreSQL,我正在尝试计算同一列中两个值的百分比变化并按名称列对它们进行分组,但我遇到了问题。

假设我有以下 table:

name day score
Allen 1 87
Allen 2 89
Allen 3 95
Bob 1 64
Bob 2 68
Bob 3 75
Carl 1 71
Carl 2 77
Carl 3 80

我希望结果是第 3 天和第 1 天之间每个人的姓名和百分比变化。所以 Allen 应该是 9.2,因为从 87 到 95 是 9.2% 的增长。

我想要的结果是:

name percent_change
Allen 9.2
Bob 17.2
Carl 12.7

感谢您的帮助。

你可以尝试使用滞后函数,像这样:

select name, day, score, 100*(score - lag(score, 1) over (partition by name order by day))/(lag(score, 1) over (partition by name order by day)) as growth_percentage 

试试这个...


    with dummy_table as (
        select
            name, 
            day, 
            score as first_day_score, 
            lag(score, 2) over (partition by name order by day desc) as last_day_score
        from YOUR_TABLE_NAME
    )
    select 
        name,  
        (last_day_score - first_day_score) / first_day_score::decimal as percentage_change 
    from dummy_table where last_day_score is not null

只需替换YOUR_TABLE_NAME。可能有更高性能和更奇特的解决方案,但这行得通。