使用 window 函数 lag() 计算百分比变化
using window function lag() to calculate percentage change
我正在尝试计算每行共享特定属性的差异。例如,我玩了三款游戏(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 BY
和 ORDER 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
)
在与 LAG()
相同的 CTE 中添加聚合 GROUP BY
将解决问题
我正在尝试计算每行共享特定属性的差异。例如,我玩了三款游戏(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 BY
和 ORDER 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
)
在与 LAG()
相同的 CTE 中添加聚合 GROUP BY
将解决问题