Search code examples
sqlsql-serverssmsssas

How to write SQL to calculate running average with some additional formulae?


Following is the image that has running average calculated by me. But the requirement is a bit extra on top of the running average.

Running average calculated already

Following is the image where the requirement is in the Microsoft Excel sheet.

Requirement on top of running average

So, in order to calculate the running average with formulae like =(3*C4+2*C5+1*C6)/6 that have been gathered in excel sheet, what SQL Query could be written?

Also, if it's not feasible through SQL, then how could I use the Column D from the second image as my measure in SSAS?


Solution

  • use LAG() with offset and follow your formula accordingly

    avg_val = ( (3.0 * lag(Open_, 2) over (order by M, [WEEK]) )
              + (2.0 * lag(Open_, 1) over (order by M, [WEEK]) )
              + (1.0 * Open_) ) / 6