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

时间:2015-02-01 21:22:41

标签: mysql dynamic max min

我正在寻找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。

1 个答案:

答案 0 :(得分:0)

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

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;