Best way to interpolate values in SQL

前端 未结 3 1120
孤独总比滥情好
孤独总比滥情好 2020-12-15 08:16

I have a table with rate at certain date :

          Rates

Id  |     Date      |  Rate
----+---------------+-------
 1  |   01/01/2011  |  4.5
 2  |   01/04         


        
3条回答
  •  长情又很酷
    2020-12-15 08:24

    The trick with CROSS JOIN here is it wont return any records if either of the table does not have rows (1 * 0 = 0) and the query may break. Better way to do is use FULL OUTER JOIN with inequality condition (to avoid getting more than one row)

    ( SELECT TOP 1 
            Date, Rate 
        FROM Rates
        WHERE Date <= @InputDate
        ORDER BY Date DESC
      ) AS prev
      FULL OUTER JOIN
      ( SELECT TOP 1 
            Date, Rate 
        FROM Rates
        WHERE Date >= @InputDate
        ORDER BY Date ASC
      ) AS next
    ON (prev.Date <> next.Date) [or Rate depending on what is unique]
    

提交回复
热议问题