首页 > 解决方案 > 计算两天之间的价格差异

问题描述

我有下表称为商店:

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;

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

标签: sqlpostgresqlwindow-functions

解决方案


差不多好了。只需从价格中减去滞后(价格):

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

推荐阅读