Mysql 如何在sql中将当前价格除以同一列中的最后一个价格
如何划分89-95/95*100或95-100/100*100Mysql 如何在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 |
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;