计算两天之间的价格差

时间:2019-05-02 08:23:52

标签: sql postgresql window-functions

我有下表称为商店:

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;

我不确定如何计算两天之间的价格差或价格上涨。更具体地说,我不知道我可以使用哪些方法来计算价格差异。任何见解都会受到赞赏。

1 个答案:

答案 0 :(得分:3)

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

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