[英]Calculate averages of previous 7 rows SQL
Consider the following result set returned from a stored procedure: 考虑从存储过程返回的以下结果集:
The goal with the IHD column, is to do a calculation of the previous 6 rows (days) to determine a IHD value from within the stored procedure. IHD列的目标是对前6行(天)进行计算,以确定存储过程中的IHD值。
In this case, only from row 7 and onwards will there be an IHD value, since the calculation needs to take into consideration the previous 6 days' closing balance including current day (day 7) and calculate an average. 在这种情况下,只有从第7行开始才有IHD值,因为计算需要考虑前6天的期末余额,包括当日(第7天)并计算平均值。 Basically, it needs to use row 1 to 7 for row's 7 IHD value.
基本上,它需要使用行1到7作为行的7 IHD值。 And then, to calculate row 8's IHD value, it needs to use row 2 to 8.
然后,要计算第8行的IHD值,需要使用第2到8行。
I have had a look at SQL LAG
function, but this only allows me to skip to 1 previous row, and I am not quite sure if I would be able to successfully use the LAG
function in a self referencing CTE
where averages of more than one previous row is required. 我看过
SQL LAG
函数,但这只允许我跳至上一行,而且我不确定我是否能够在平均多个以上的自引用CTE
中成功使用LAG
函数。前一行是必需的。
How should I approach this scenario? 我应该如何处理这种情况?
Use ROWS BETWEEN
. 在之间使用
ROWS BETWEEN
。 Without Consumable sample data and expected results I can only give Pseudo SQL, but this'll put you on the right path: 没有消耗性的示例数据和预期的结果,我只能提供伪SQL,但这将使您走上正确的道路:
AVG({Your Column}) OVER ([PARTITION BY {Other Column}] ORDER BY {Column To Order BY}
ROWS BETWEEN 6 PRECEDING AND CURRENT ROW)
Obviously replace the parts in braces ( {}
) and remove the parts in brackets ( []
) if not required. 显然,如果不需要,请用大括号(
{}
)装回零件,并卸下括号( []
)的零件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.