sql - Getting the average over the first n rows -
i'm trying devise sql query can take column of results , return average/mean of first "n" results.
in other words, if have sample of data looks this:
| day | number of people | |:-----:|:----------------:| | 12/01 | 4 | | 12/02 | 8 | | 12/03 | 5 | | 12/04 | 6 | | 12/05 | 8 | | 12/06 | 3 | | 12/07 | 5 |
i want query can result in table looking this:
| day | number of people | nmean | |:-----:|:----------------:|:------:| | 12/01 | 4 | 4 | | 12/02 | 8 | 6 | | 12/03 | 5 | 5.6667 | | 12/04 | 6 | 5.75 | | 12/05 | 8 | 6.2 | | 12/06 | 3 | 5.6667 | | 12/07 | 5 | 5.5714 |
you can have elegant solution if use window functions.
though works in sql server 2012 , later.
select d.[day], avg(d.[num] * 1.0) on ( order d.[day] asc rows between unbounded preceding , current row ) nmean [data] d;
this should work (even in sql server 2008):
select d2.[day], avg(1.0 * d1.num) nmean data d2 join data d1 on d2.day >= d1.day group d2.[day] order d2.[day] asc;
Comments
Post a Comment