Dynamic minimum value for specfic range (mysql)

对着背影说爱祢 提交于 2019-12-24 11:29:58

问题


I am looking for a solution to SELECT (or otherwise derive) the values for Column C (minimum price for last 3 days only, not for the whole column).

----------------------------------------
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  | 
----------------------------------------

My thought revolves around the following, but yielding an error:

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

What is the correct query to get this to work? Database used MySQL.


回答1:


You are pretty close. When working with correlated subqueries, always use table aliases to be absolutely clear about where the columns are coming from:

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;


来源:https://stackoverflow.com/questions/28268070/dynamic-minimum-value-for-specfic-range-mysql

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!