特定范围的动态最小值 (mysql)

Dynamic minimum value for specfic range (mysql)

我正在寻找 SELECT(或以其他方式导出)C 列的值(仅过去 3 天的最低价格,而不是整个列的最低价格)的解决方案。

----------------------------------------
Date          | Unit_ | Low_3_days     | 
              | price |                | 
----------------------------------------
2015-01-01    | 15    | should be: 15  | 
2015-01-02    | 17    | should be: 15  | 
2015-01-03    | 21    | should be: 15  | 
2015-01-04    | 18    | should be: 17  | 
2015-01-05    | 12    | should be: 12  | 
2015-01-06    | 14    | should be: 12  |
2015-01-07    | 16    | should be: 12  | 
----------------------------------------

我的想法围绕以下,但产生了一个错误:

select S.Date,Unit_price, 
      (SELECT min(LOW_3_days) 
         FROM table 
        where S.DATE BETWEEN S.DATE-1 
                         and S.DATE-3) 
           AS min_price_3_days
  FROM table AS S

让它工作的正确查询是什么?使用的数据库 MySQL.

你很接近。使用相关子查询时,请始终使用 table 别名以绝对清楚列的来源:

select S.Date, Unit_price, 
       (SELECT min(s2.Unit_Price) 
        FROM table s2
        WHERE s2.DATE BETWEEN s.DATE - interval 3 day and
                              s.DATE - interval 1 day
       ) as min_price_3_days
FROM table S;