【发布时间】:2020-12-31 15:23:32
【问题描述】:
我有一个结构如下的表:
| id | col1 | col2 |
|---|---|---|
| 1 | 1 | 0 |
| 2 | 1 | 1 |
| 3 | 1 | 0 |
| 4 | 1 | 2 |
| 5 | 1 | 1 |
| 6 | 1 | 2 |
| 7 | 1 | 1 |
我想得到以下结果:
| id | col1 | col2 | col3 |
|---|---|---|---|
| 1 | 1 | 0 | 1 |
| 2 | 1 | 1 | 1 |
| 3 | 2 | 0 | 3 |
| 4 | 0 | 2 | 1 |
| 5 | 3 | 1 | 3 |
| 6 | 0 | 2 | 1 |
| 7 | 0 | 1 | 0 |
其中 col3= 上一行的 col3 值 + col1 值 - col2 值
我添加了一列这样的零:
| id | col1 | col2 | col3 |
|---|---|---|---|
| 1 | 1 | 0 | 0 |
| 2 | 1 | 1 | 0 |
| 3 | 2 | 0 | 0 |
| 4 | 0 | 2 | 0 |
| 5 | 3 | 1 | 0 |
| 6 | 0 | 2 | 0 |
| 7 | 0 | 1 | 0 |
并尝试了以下查询:
select col1, col2,
lag(col3) over (order by id) + col1 - col2 as col3
from t1;
但是我无法获得想要的结果。我想得到一些帮助。
【问题讨论】:
-
SQL 表代表 无序 集。如果没有指定顺序的列,就没有“前一个”行或值。
-
有一个'id'列,更新问题
标签: sql postgresql