Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/55.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Mysql 如何在sql中将当前价格除以同一列中的最后一个价格_Mysql_Sql - Fatal编程技术网

Mysql 如何在sql中将当前价格除以同一列中的最后一个价格

Mysql 如何在sql中将当前价格除以同一列中的最后一个价格,mysql,sql,Mysql,Sql,如何划分89-95/95*100或95-100/100*100 CREATE TABLE `priceindex` ( `priceIndexId` int(11) NOT NULL, `Date` date DEFAULT NULL, `Price` decimal(31,9) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; priceIndexId |

如何划分89-95/95*100或95-100/100*100

 CREATE TABLE `priceindex` (
          `priceIndexId` int(11) NOT NULL,
          `Date` date DEFAULT NULL,
          `Price` decimal(31,9) DEFAULT NULL
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8;


priceIndexId |    Date    | Price | Currentvalue/previous value
      1      | 2017-11-30 |  100  | 
      2      | 2017-12-06 |  95   | answer should be(95-100)/100)*100 = -0.50
      3      | 2017-12-13 |  89   | answer should be(89-95)/95)*100 = -0.63

提前感谢

您需要获取上一个值。一种方法使用相关子查询。我建议使用子查询进行计算:

select pi.priceIndexId, pi.Date, pi.Price,
       (pi.Price - pi.prev_price) / pi.prev_price as change
from (select pi.*,
             (select pi2.price
              from priceindex pi2
              where pi2.date < pi.date
              order by pi2.date desc
              limit 1
             ) as prev_price
      from priceindex pi
     ) pi;