Skip to content
Advertisement

SQL query to interpolate between values

I intend to interpolate (linear interpolation) between values in a column and insert that into a new column using a SQL query. Based on my search online, I suspect LEAD analytic function could be useful. I am new to writing SQL queries. So, any insights on how it can be achieved will be quite helpful.

The sample data set is as described:

The idea is to get a fourth column that has values as:

Interpolatedvalue1 would be an interpolated value between 100 and 80,

Interpolatedvalue2 would be a linearly interpolated value between 80 and 75.

InterpolatedValue3 would be a linearly interpolated value between Interpolatedvalue2 and 75

Here’s how a simple linear interpolation works:

Given two points (V1 at D1), (V3 at D3). What would be the value V2 at D2?

(V3-V1)/(D3-D1) * (D2-D1) + V1

Advertisement

Answer

This can probably be simplified a bit but gets the answer you wanted, I believe. The slightly tricky bit is getting both the number of days between not-null values (i.e. the size of the gap you’re filling) and then the position within that gap:

I’ve used last_value and first_value instead of lead and lag, but either works. (Lead/lag might be faster on a large data set I suppose). The grp calculation is Tabibitosan.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement