计算两天的价差

Calculating the price difference between two days

我有以下 table 商店:

Date        |  Store  |  Price
2018-05-02  |  ABC    |  0.91
2018-05-02  |  DEF    |  0.81
2018-05-03  |  ABC    |  0.92
2018-05-03  |  DEF    |  0.83
2018-05-05  |  ABC    |  0.91
2018-05-05  |  DEF    |  0.85

我正在尝试为给定的商店编写一个查询,该查询将输出价格、前一天的价格以及两天之间的价格差异和价格收益(百分比) .输出应如下所示:

 Date        |  Store  |  Price  |  PrevPrice  |  Change  |  Gain
 2018-05-03  |  ABC    |  0.92   |  0.91       |  0.01    |  1.086956522
 2018-05-05  |  ABC    |  0.91   |  0.92       |  -0.01   |  -1.098901099
 2018-05-03  |  DEF    |  0.83   |  0.81       |  0.02    |  2.409638554
 2018-05-05  |  DEF    |  0.85   |  0.83       |  0.02    |  2.352941176

第一个日期不应出现在输出中,因为它没有之前的日期。 我有以下使用 lag() 获取 PrevPrice 的查询:

select * 
from (
    select "Date", store, price, lag(price) over (partition by code order by "Date") as PrevPrice from Stores
) s where PrevPrice is not null;

我不确定如何计算两天之间的价格差异或价格收益。更具体地说,我不知道我可以使用什么方法来计算差价。任何见解表示赞赏。

快到了。只需从价格中减去滞后(价格):

SELECT Date, Store, Price, PrevPrice, Price - PrevPrice AS Change, (Price - PrevPrice) / PrevPrice * 100 AS Gain
FROM (
    SELECT Date, Store, Price, LAG(Price) OVER (PARTITION BY Store ORDER BY Date) AS PrevPrice
    FROM t
) AS x
WHERE PrevPrice IS NOT NULL