Search code examples
sqlsql-servermoving-averagerolling-average

Calculate and store average for following table in SQL Server


I am trying to calculate average of P value in following table as per month in per_date column grouped by qu_def column.

enter image description here

and store it as follows in a SQL Server table:

enter image description here


Solution

  • You seem to want a query like this:

    select qu_def, for_cur,
           datefromparts(year(per_date), month(per_date), 1) as per_date,
           max(per_date) as date, avg(p) as p
    from t
    group by qu_def, for_cur,
           datefromparts(year(per_date), month(per_date), 1);
    

    You can use INSERT to put this in an existing table or INTO to create a new table.