简体   繁体   中英

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.

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. Basically, it needs to use row 1 to 7 for row's 7 IHD value. And then, to calculate row 8's IHD value, it needs to use row 2 to 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.

How should I approach this scenario?

Use ROWS BETWEEN . Without Consumable sample data and expected results I can only give Pseudo SQL, but this'll put you on the right path:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM