Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the running average of a column in T-SQL

Okay so I have a table and in one column I have some data and the second column the average of the data. Example

id|Data|avg
1 |20  |20
2 |4   |12
3 |18  |14

How do I populate the avg column on insert with the running average of the Data column using T-SQL?

EDIT: Sorry guys, this was actually a stupid mistake I made. I assumed I had SQL 2014 but after trying Stephan's code and getting some errors, I went back to confirm and realize I use SQL 2008. Sorry for the misinformation. I have also updated the tags

like image 648
MRainzo Avatar asked Dec 09 '22 03:12

MRainzo


1 Answers

On insert, assuming id is an identity and you are just putting in data:

insert into table t(id, data, avg)
    select @data, @data * (1.0 / n) + avg * (n - 1.0)/n
    from (select count(*) as cnt, avg(data) as avg
          from t
         ) t;

In SQL Server 2012+, it is easy enough just to get it on output:

select t.*, avg(data) over (order by id) as cume_avg
from table t

Prior to SQL Server 2012, you would do this with a correlated subquery or apply:

select t.*,
       (select avg(data)
        from table t2
        where t2.id <= t.id
       ) as cume_avg 
from table t;

Here performance might suffer if the table is large. However, an index on id, data would help.

like image 174
Gordon Linoff Avatar answered Dec 15 '22 16:12

Gordon Linoff