[英]Dynamically add previous row value to current row value in SQL(Postgres)
我有一個具有以下結構的表:
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;
但是我無法獲得預期的結果。 我想得到一些幫助。
您只需要分析 function sum
如下:
select col1, col2,
Sum(col1 - col2) over (order by id) as col3
from t1;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.