MySQL 按范围内的日期计算跨行的百分比

MySQL calculate percentage across rows by dates in a range

我正在使用 MySQL 5.6,我有一个 table 包含很多这样的记录...

+----+------------+-------+
| id | date       | price |
+----+------------+-------+
|  1 | 2000-01-01 |  1.56 |
|  1 | 2000-01-05 |  1.90 |
|  1 | 2000-02-02 |  1.44 |
|  2 | 2000-01-01 | 10.99 |
|  2 | 2000-01-07 |  9.88 |
|  2 | 2000-02-01 |  9.64 |
+----+------------+-------+

对于每个 ID,我想 return 以下...

  1. ID
  2. 最短日期 >= 1 个月前
  3. 最大日期 <= 今天的日期
  4. 价格的百分比差异,基于 2 个日期的价格 returned
  5. 甚至可能显示那些日期的价格

例如如果 table 数据是(今天是 2000-02-01)...

+----+------------+-------+
| id | date       | price |
+----+------------+-------+
|  1 | 2000-01-01 |  1.00 |
|  1 | 2000-02-01 |  1.10 |
|  2 | 2000-01-04 |  1.00 |
|  2 | 2000-02-01 |  2.00 |
+----+------------+-------+

那么我希望看到...

+----+------------+------------+------------+
| id | min        | max        | percentage |
+----+------------+------------+------------+
|  1 | 2000-01-01 | 2000-02-01 |        10% |
|  2 | 2000-01-04 | 2000-02-01 |       100% |
+----+------------+------------+------------+

所以我的问题是,我该怎么做?更重要的是,解决这个问题的逻辑步骤是什么?

你可以从这里开始,它还有很大的改进空间:

DROP TABLE IF EXISTS price;
CREATE TABLE price (id int ,`date` date,price decimal(8,2));
INSERT INTO price VALUES
('1','2000-01-01','1.56'),
('1','2000-01-05','1.90'),
('1','2000-02-02','1.44'),
('2','2000-01-01','10.99'),
('2','2000-01-07','9.88'),
('2','2000-02-01','9.64');


select id,`min`,`max`,`price1`,`price2`,
    round((price2-price1)/price1*100,2) as `percentage`
from (
   select id,`min`,`max`,
       (select price from price p1 where p1.id=x.id and p1.`date`=x.`min`) as price1,
       (select price from price p1 where p1.id=x.id and p1.`date`=x.`max`) as price2
   from (
      select 
         id,
         min(`date`) as `min`,
         max(`date`) as `max`
      from price
      where `date` between '2000-01-01' and '2000-02-01'
      -- where `date` between date_add(current_date(), INTERVAL -1 month) and current_date()
      group by id) x
   ) x2;

注意:注释的WHERE子句用于过滤当前日期之前的最后一个月。使用的 WHERE 子句只是为了使其与示例数据一起使用。

注意 2:我将 table 命名为 price 因为问题中没有给出名称。我确实需要一个更适合您当前情况的解决方案,您应该为您使用的 table 提供 create table... (DDL) 以及一些样本数据。

注意 3:您不应使用 Reserved words 作为列名,例如此代码中的 dateminmax...