Interpolate missing values in a MySQL table

前端 未结 3 1507
夕颜
夕颜 2021-01-13 20:06

I have some intraday stock data saved into a MySQL table which looks like this:

+----------+-------+
| tick     | quote |
+----------+-------+
| 08:00:10 |           


        
3条回答
  •  孤城傲影
    2021-01-13 21:05

    I would create a (temporary) table with the same layout as your table and run the following two queries:

    Insert all interpolations into the temp_stock table

    INSERT INTO temp_stock (tick, quote) 
      SELECT s2.tick
             , (s1.quote + s3.quote) /2 as quote
      FROM stock 
      INNER JOIN stock s1 ON (s1.tick < s2.tick) 
      INNER JOIN stock s3 ON (s3.tick > s2.tick) 
      WHERE s2.quote IS NULL
      GROUP BY s2.tick
      HAVING s1.tick = MAX(s1.tick), s3.tick = MIN(s3.tick)  
    

    Update the stock table with the temp values

      UPDATE stock s 
      INNER JOIN temp_stock ts ON (ts.tick = s.tick) SET s.quote = ts.quote
    

    It does use a temp table (make sure it's a memory table for speed), but it doesn't need a cursor.

提交回复
热议问题