r/DatabaseHelp • • Apr 19 '16

Average of every N rows, with SQLite?

Lets say for table:

Col1Col2
4Bar
2Foo
6Baz
9Banana
10FooBar
5Apple

It would return

Col1(This is math, not actual return)
3(4+2)/2
7.5(6+9)/2
7.5(10+5)/2

I can do this with backend code w/o problems, but letting SQ do most if data-related work, is better idea, right?

2 Upvotes

9 comments sorted by

View all comments

Show parent comment

1

u/MRoka5 Apr 19 '16

I've timestamp column too, so sorting wouldnt be that much of problem.

Atm, I'm using PHP to calculate averages of 5, but offloading data-related calculations to SQL, can reduce load time by nice margin.

1

u/wolf2600 Apr 19 '16

How did you do it in PHP?

And as was mentioned, unless you explicitly include an ORDER BY statement, the order that the rows will be returned might never be the same (assume that you're getting back an unordered data set, not a list... which is why doing comparisons on "first 3 records" is almost never used in SQL).

The rows don't have a value which is unique for each set you want to average? Like for the first two rows, the value is 1, second two it's 2, third two it's 3??

1

u/MRoka5 Apr 19 '16

For loop, with +n increment.

No, sadly they dont have unique values / group. :/