sql - 计算两天之间的价格差异
问题描述
我有下表称为商店:
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
推荐阅读
- spring-boot - 用于 Spring Boot 的 Typesafe @Qualifier 以避免字符串错误
- ios - 在照片应用 IOS FLUTTER 中下载和显示图像
- python - 基于“日期”组制作新数据框。但是每个新列都是“值的计数”
- sql - 如何在 regex_replace() 中使用 db 列名 - presto
- python - 我要从淘宝上获取 Selenium 的视频。我被困在blob中
- applescript - JXA 设置窗口边界奇怪的问题
- android - 使用 SSL 证书锁定信任锚模式后的 Ionic ion-img 已损坏
- swift - 如何使用@MainActor 初始化全局变量?
- python - 如何在 argparse 中嵌套自定义参数解析器实例
- angular - Angular-testing-library - 当期望错误值时我的测试没有失败