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

Popular posts from this blog

javascript - How to synchronize the Three.js and HTML/SVG coordinate systems (especially w.r.t. the y-axis)? -

javascript - How do I find how many occurences are there of a highlighted string, and which occurence is it? -

java - Reading data from multiple zip files and combining them to one -