Search code examples
sqlsql-server-2005interpolationlinear-interpolation

Best way to interpolate values in SQL


I have a table with rate at certain date :

          Rates

Id  |     Date      |  Rate
----+---------------+-------
 1  |   01/01/2011  |  4.5
 2  |   01/04/2011  |  3.2
 3  |   04/06/2011  |  2.4
 4  |   30/06/2011  |  5

I want to get the output rate base on a simple linear interpolation.

So if I enter 17/06/2011:

Date        Rate
----------  -----
01/01/2011  4.5
01/04/2011  3.2
04/06/2011  2.4
17/06/2011  
30/06/2011  5.0

the linear interpolation is (5 + 2,4) / 2 = 3,7

Is there a way to do a simple query (SQL Server 2005), or this kind of stuff need to be done in a programmatic way (C#...) ?


Solution

  • Something like this (corrected):

    SELECT CASE WHEN next.Date IS NULL  THEN prev.Rate
                WHEN prev.Date IS NULL  THEN next.Rate
                WHEN next.Date = prev.Date  THEN prev.Rate
                  ELSE ( DATEDIFF(d, prev.Date, @InputDate) * next.Rate 
                       + DATEDIFF(d, @InputDate, next.Date) * prev.Rate
                       ) / DATEDIFF(d, prev.Date, next.Date)
           END AS interpolationRate 
    FROM
      ( SELECT TOP 1 
            Date, Rate 
        FROM Rates
        WHERE Date <= @InputDate
        ORDER BY Date DESC
      ) AS prev
      CROSS JOIN
      ( SELECT TOP 1 
            Date, Rate 
        FROM Rates
        WHERE Date >= @InputDate
        ORDER BY Date ASC
      ) AS next