Get Average value for each X rows in SQL
NickName:Douglas Vanny Ask DateTime:2014-02-08T13:26:29

Get Average value for each X rows in SQL

Let`s say I have the following table

+----+-------+
| Id | Value |
+----+-------+
|  1 |   2.0 |
|  2 |   8.0 |
|  3 |   3.0 |
|  4 |   9.0 |
|  5 |   1.0 |
|  6 |   4.0 |
|  7 |   2.5 |
|  8 |   6.5 |
+----+-------+

I want to plot these values, but since my real table has thousands of values, I thought about getting and average for each X rows. Is there any way for me to do so for, ie, each 2 or 4 rows, like below:

2
+-----+------+
| 1-2 |  5.0 |
| 3-4 |  6.0 |
| 5-6 |  2.5 |
| 7-8 |  4.5 |
+-----+------+

4
+-----+------+
| 1-4 |  5.5 |
| 5-8 |  3.5 |
+-----+------+

Also, is there any way to make this X value dynamic, based on the total number of rows in my table? Something like, if I have 1000 rows, the average will be calculated based on each 200 rows (1000/5), but if I have 20, calculate it based on each 4 rows (20/5).

I know how to do that programmatically, but is there any way to do so using pure SQL?

EDIT: I need it to work on mysql.

Copyright Notice:Content Author:「Douglas Vanny」,Reproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/21642329/get-average-value-for-each-x-rows-in-sql

Answers
ErikE 2014-02-08T05:54:27

Depending on your DBMS, something like this will work:\n\nSELECT\n ChunkStart = Min(Id),\n ChunkEnd = Max(Id),\n Value = Avg(Value)\nFROM\n (\n SELECT\n Chunk = NTILE(5) OVER (ORDER BY Id),\n *\n FROM\n YourTable\n ) AS T\nGROUP BY\n Chunk\nORDER BY \n ChunkStart;\n\n\nThis creates 5 groups or chunks no matter how many rows there are, as you requested.\n\nIf you have no windowing functions you can fake it:\n\nSELECT\n ChunkStart = Min(Id),\n ChunkEnd = Max(Id),\n Value = Avg(Value)\nFROM\n YourTable\nGROUP BY\n (Id - 1) / (((SELECT Count(*) FROM YourTable) + 4) / 5)\n;\n\n\nI made some assumptions here such as Id beginning with 1 and there being no gaps, and that you would want the last group too small instead of too big if things didn't divide evenly. I also assumed integer division would result as in Ms SQL Server.",


Miro 2014-02-08T05:45:41

You can use modulos operator to act on every Nth row of the table. This example would get the average value for every 10th row:\n\nselect avg(Value) from some_table where id % 10 = 0;\n\n\nYou could then do a count of the rows in the table, apply some factor to that, and use that value as a dynamic interval:\n\nselect avg(Value) from some_table where id % (select round(count(*)/1000) from some_table) = 0;\n\n\nYou'll need to figure out the best interval based on the actual number of rows you have in the table of course.\n\nEDIT:\nRereading you post I realize this is getting an average of every Nth row, and not each sequential N rows. I'm not sure if this would suffice, or if you specifically need sequential averages. ",


Concrete Gannet 2014-02-08T05:56:03

Look at the NTILE function (as in quartile, quintile, decile, percentile). You can use it to split your data evenly into a number of buckets - in your case it seems you would like five.\n\nThen you can use AVG to calculate an average for each bucket.\n\nNTILE is in SQL-99 so most DBMSes should have it.",


More about “Get Average value for each X rows in SQL” related questions

Get Average value for each X rows in SQL

Let`s say I have the following table +----+-------+ | Id | Value | +----+-------+ | 1 | 2.0 | | 2 | 8.0 | | 3 | 3.0 | | 4 | 9.0 | | 5 | 1.0 | | 6 | 4.0 | | 7 |

Show Detail

SQL average value for multiple rows

I got a table which can be simplefied to to following columns: [A] | [B] | [C] | [D] | [Value] With my basic query I get 3 or 4 rows (it varies) where A, B, C and D is identical, but with different

Show Detail

Getting average of selected rows for each column pandas

I want to be able to get the average of the last 4 rows that are in 'Stage' 2, for each column. Sample Data Currently I am using av = df.loc[df['Stage'] == 2, 'Vout'].mean() but this gives me the

Show Detail

Get the average column values for a set of rows using R

I am trying to get the mean value of a column over a certain range of rows. For example, suppose: data.frame(x=c(.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9)) I want the average value of Rows 1-3, 4-6, an...

Show Detail

How to get the average of the last X values?

If I have a table with two columns - value and time_stamp - how can I use SQL to get the average of the last X values? One statement or several, it doesn't matter. Maybe something like SELECT value...

Show Detail

Average of a column for the bottom N rows for each group in a table

I want to get the average of a column for the last 5 rows (if there are less than 5 rows (games) for a player then it should return nothing..) If I could use a subquery then it would be straight f...

Show Detail

How to get the average maximum value between rows with a given step?

I need to get in columns the average maximum value between two rows with n steps. If the step is 6 (n = 6), I need to find out the average maximum value between 1 and 6 (not inclusive) rows, then b...

Show Detail

Average n rows for each part and then last n rows for the same part

I have a csv file which has about 10 rows of output values along with temperature measurements for each part. There are about 100 parts. But I want the following: Average only first 3 rows for eac...

Show Detail

How to divide each value of 10 rows by the average of the next two rows for each column of data frame?

I would like to divide each of the values for 10 samples/rows by the average of the 2 subsequent rows. For example, in my mock data this would be each of the values in my 1:10 rows, divided by the

Show Detail

Sorting some rows by average with SQL

All right, so here's a challenge for all you SQL pros: I have a table with two columns of interest, group and birthdate. Only some rows have a group assigned to them. I now want to print all rows s...

Show Detail