使用 SQL windows 分析函数计算百分比变化
Calculating percentage change with SQL windows analytic function
我正在使用下面的 table 计算某个科目在学期内总分的百分比变化。
name subject session term totalscore
-------------------------------------------
jack maths 2013/2014 1 70
jack eng 2013/2014 1 65
jack science 2013/2014 1 80
jack maths 2013/2014 2 72
jack eng 2013/2014 2 87
jack science 2013/2014 2 67
jack maths 2013/2014 3 70
jack eng 2013/2014 3 70
jack science 2013/2014 3 85
我尝试使用如下所示的 windows LAG 函数来计算总分百分比变化,但在 percentage_change 列
中得到 NULL 值
SELECT
name,
subject,
term,
session,
totalscores - lag(totalscores, 1) over(partition by subject, session, term order by session, term) / 100*100
FROM
totalscore
GROUP BY
name, subject, session, term, totalscores
ORDER BY
term
预期结果 table 看起来像这样
name subject session term totalscore percent_change
------------------------------------------------------------
jack maths 2013/2014 1 70 null
jack eng 2013/2014 1 65 null
jack science 2013/2014 1 80 null
jack maths 2013/2014 2 72 2%
jack eng 2013/2014 2 87 22%
jack science 2013/2014 2 67 -5%
jack maths 2013/2014 3 70 -2%
jack eng 2013/2014 3 70 -17%
jack science 2013/2014 3 85 16%
有什么方法可以帮助修复这个错误吗?我将不胜感激我能得到的任何帮助。谢谢。
您似乎只想要差异(因为这些已经是百分比)。但关键是让 partition by
正确对应 lag()
:
select name, subject, term, session,
(totalscores -
lag(totalscores) over(partition by name, subject order by session, term)
) as diff
from totalscore
order by name, subject, session, term;
我正在使用下面的 table 计算某个科目在学期内总分的百分比变化。
name subject session term totalscore
-------------------------------------------
jack maths 2013/2014 1 70
jack eng 2013/2014 1 65
jack science 2013/2014 1 80
jack maths 2013/2014 2 72
jack eng 2013/2014 2 87
jack science 2013/2014 2 67
jack maths 2013/2014 3 70
jack eng 2013/2014 3 70
jack science 2013/2014 3 85
我尝试使用如下所示的 windows LAG 函数来计算总分百分比变化,但在 percentage_change 列
中得到 NULL 值SELECT
name,
subject,
term,
session,
totalscores - lag(totalscores, 1) over(partition by subject, session, term order by session, term) / 100*100
FROM
totalscore
GROUP BY
name, subject, session, term, totalscores
ORDER BY
term
预期结果 table 看起来像这样
name subject session term totalscore percent_change
------------------------------------------------------------
jack maths 2013/2014 1 70 null
jack eng 2013/2014 1 65 null
jack science 2013/2014 1 80 null
jack maths 2013/2014 2 72 2%
jack eng 2013/2014 2 87 22%
jack science 2013/2014 2 67 -5%
jack maths 2013/2014 3 70 -2%
jack eng 2013/2014 3 70 -17%
jack science 2013/2014 3 85 16%
有什么方法可以帮助修复这个错误吗?我将不胜感激我能得到的任何帮助。谢谢。
您似乎只想要差异(因为这些已经是百分比)。但关键是让 partition by
正确对应 lag()
:
select name, subject, term, session,
(totalscores -
lag(totalscores) over(partition by name, subject order by session, term)
) as diff
from totalscore
order by name, subject, session, term;