I want to calculate a value by interpolating the value between two nearest neighbours. I have a subquery that returns the values of the neighbours and their relative distance, in the form of two columns with two elements.
Let's say:
(select ... as value, ... as distance
from [get some neighbours by distance] limit 2) as sub
How can I calculate the value of the point by linear interpolation? Is it possible to do that in a single query?
Example: My point has the neighbour A with value 10 at distance 1, and the neighbour B with value 20 at distance 4. The function should return a value 10 * 4 + 20 * 1 / 5 = 12
for my point.
I tried the obvious approach
select sum(value * (sum(distance)-distance)) / sum(distance)
which will fail because you cannot work with group clauses inside group clauses. Using another subquery returning the sum is not possible either, because then I cannot forward the individual values at the same time.
If you actually want the
point
in between, there is a built-in way of doing that (but not an aggregate function):If you want the mean distance:
See geometrical function and aggregate functions in the manual.
Edit:
For the added example, the query could look like this:
I added missing
()
to get the result you expect!Or, my last stab at it:
It would be so much easier, if you provided the full query and the table definitions.
This is an ugly hack (based on a abused CTE ;). The crux of it is that
Can, by dividing by distance1*distance2, be rewritten to
So, the products (or divisions) can stay inside their rows. After the summation, multiplying by (distance1*distance2) rescales the result to the desired output. Generalisation to more than two neighbors is left as an exercise to the reader.YMMV
The result:
Update: this one is a bit cleaner ... ties are still not handled (need a window function or a LIMIT 1 clause in the outer query for that)