sql - Creating a Separate Column for Prior Week Values (PostgreSQL)
问题描述
How would I go about having a separate column that shows the prior week's value? For example, if Product A
's value for 01/03/2021
was 100
, I would like 01/10/2021
to show its date value as well as the 01/03/2021
value in a separate column.
Desired table below (for simplicity sake I added random numbers for the prior week values for 01/03
and 01/04
):
Date | Product | Value | Prior Week Value |
---|---|---|---|
01/03/2021 | Product A | 100 | 50 |
01/04/2021 | Product A | 200 | 55 |
01/10/2021 | Product A | 600 | 100 |
01/11/2021 | Product A | 700 | 200 |
01/03/2021 | Product B | 250 | 40 |
01/04/2021 | Product B | 550 | 45 |
01/10/2021 | Product B | 460 | 250 |
01/11/2021 | Product B | 100 | 550 |
解决方案
If you want exactly 7 days before, you can use window functions with a range specification:
select t.*,
max(value) over (partition by product
order by date
range between '7 day' preceding and '7 day' preceding
) as value_prev_week
from t;
推荐阅读
- javascript - 如何获得品牌属性的价值?
- javascript - 如何从网站 javascript 中获取价值?
- python - 重复高阶函数
- javascript - Angular - 输入预测值调用 api
- javascript - NodeJS:如何使用 Loopback4 建立多对多关系
- windows - 在 Windows 容器模式下的 Windows 10 上,Docker 拉取失败
- reactjs - 警告:无法对未安装的组件执行 React 状态更新......componentWillUnmount 方法
- python - Pandas 只合并 SQLite 数据库中的新数据
- python - 如何将 matplotlib.pypot 图保存为具有所需像素大小的图像?
- actions-on-google - 在自定义谷歌操作中使用个性化信息