使用窗口函数lag()计算百分比变化

时间:2018-12-21 02:20:50

标签: sql postgresql lag window-functions database-partitioning

我正在尝试计算每个共享特定属性的每一行之间的差异。例如,我有一个星期的时间可以玩三个游戏(RDR2,GTA5,Spyro),并且已经计算出每天花在每个游戏上的百分比,并且我想看看每天变化的百分比。

因此,我写道:

percent - LAG(percent, 1) OVER (PARTITION BY game ORDER BY time DESC) AS games_delta

但未获得所需的输出:

 |-------------------------------|
 | TIME    GAME   PERCENT  DELTA |
 |-------------------------------|
 | Dec 10  RDR2   25       15    |
 | Dec 10  GTA5   50       40    |
 | Dec 10  Spyro  25      -55    |
 | Dec 9   RDR2   10      -22    |
 | Dec 9   GTA5   10       10    |
 | Dec 9   Spyro  80       13    |
 | Dec 8   RDR2   33       ...
 | Dec 8   GTA5   0        ...
 | Dec 8   Spyro  67       ...

我得到了很多游戏,完全错了game-delta!:

 |-------------------------------|
 | TIME    GAME   PERCENT  DELTA |
 | Dec 10  RDR2   25       2     |
 | Dec 10  RDR2   25       4     |
 | Dec 10  RDR2   25      -4     |
 | Dec 10  RDR2   25       4     |
 | Dec 10  GTA5   10       5  ...

有什么建议吗?预先感谢!

编辑:

SELECT  time,
        game,
        percent,
        games_delta

我的GROUP BYORDER BY中也包含以下内容:

GROUP BY time, game, percent, games_delta
ORDER BY time DESC

编辑2:

这是我的CTE:

cte_table4 (time, games_delta) AS
(
    SELECT time,
            percent - LAG(percent, 1) OVER (PARTITION BY game ORDER BY time DESC) AS games_delta

    FROM cte_table3
)

1 个答案:

答案 0 :(得分:0)

在与GROUP BY相同的 CTE中添加聚合LAG()将解决此问题