[英]using window function lag() to calculate percentage change
I'm trying to calculate the difference between each row that each shares a specific attribute.我正在尝试计算每行共享特定属性的每一行之间的差异。 For example, I have a week's worth of playtime of three games (RDR2, GTA5, Spyro) and I have calculated what percent of each day is spent on each game and I want to see what the percent change is day over day.例如,我有一周的三款游戏(RDR2、GTA5、Spyro)的游戏时间,我计算了每天在每款游戏上花费的百分比,我想看看每天的百分比变化是多少。
Hence, I wrote:因此,我写道:
percent - LAG(percent, 1) OVER (PARTITION BY game ORDER BY time DESC) AS games_delta
but instead of getting the desired output of:但不是获得所需的输出:
|-------------------------------|
| 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 ...
I get multiplicities of the games and totally wrong game-delta
!:我得到了游戏的多样性和完全错误的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 ...
Any suggestions?有什么建议? Thanks in advance!提前致谢!
Edit:编辑:
SELECT time,
game,
percent,
games_delta
I also have the following in my GROUP BY
and ORDER BY
:我的GROUP BY
和ORDER BY
还有以下内容:
GROUP BY time, game, percent, games_delta
ORDER BY time DESC
Edit 2:编辑2:
Here's my CTE:这是我的 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
将解决该问题
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.