SQL 在同一行上迭代
我正在寻找 SQL 代码来执行此操作:
tab_input
ID | Dat | A |
---|---|---|
a | 7 | 3 |
a | 6 | 4 |
a | 5 | 1 |
b | 2 | 5 |
b | 3 | 9 |
b | 1 | 2 |
我想计算一个新列 B[i] = A[i] + B [i-1],但当 ID 更改时,字段 B 会重置
tab_output
ID | Dat | A | B |
---|---|---|---|
a | 5 | 1 | 1 |
a | 6 | 4 | 5 |
a | 7 | 3 | 8 |
b | 1 | 2 | 2 |
b | 2 | 5 | 7 |
b | 3 | 9 | 16 |
我尝试了以下方法:
select
A
, A + lag( B, 1) OVER( partition by id order by dat ) as B
FROM(
select
ID, A, 0 as B
FROM tab_input
) as base
;
但它不起作用,结果是
ID | Dat | A | B |
---|---|---|---|
a | 5 | 1 | 1 |
a | 6 | 4 | 4 |
a | 7 | 3 | 3 |
b | 1 | 2 | 2 |
b | 2 | 5 | 5 |
b | 3 | 9 | 9 |
我认为它是添加到所有 0 的值并且不会更新 B 的值
我非常感谢您的帮助!
I am looking for SQL code to do this:
tab_input
ID | Dat | A |
---|---|---|
a | 7 | 3 |
a | 6 | 4 |
a | 5 | 1 |
b | 2 | 5 |
b | 3 | 9 |
b | 1 | 2 |
I want to calculate a new column B[i] = A[i] + B[i-1], but field B is reset when the ID changes
tab_output
ID | Dat | A | B |
---|---|---|---|
a | 5 | 1 | 1 |
a | 6 | 4 | 5 |
a | 7 | 3 | 8 |
b | 1 | 2 | 2 |
b | 2 | 5 | 7 |
b | 3 | 9 | 16 |
I tried the following:
select
A
, A + lag( B, 1) OVER( partition by id order by dat ) as B
FROM(
select
ID, A, 0 as B
FROM tab_input
) as base
;
But it doesn't work, the result is
ID | Dat | A | B |
---|---|---|---|
a | 5 | 1 | 1 |
a | 6 | 4 | 4 |
a | 7 | 3 | 3 |
b | 1 | 2 | 2 |
b | 2 | 5 | 5 |
b | 3 | 9 | 9 |
I think that it is adding to all the value of 0 and does not update the value of B
I am thank full your help!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
LAG
查看一行(默认情况下是当前行之前的一行)。您为每一行创建一个值为 0 的 B,然后查看 LAG(b),但前一行中的 b 也为 0;所有行都是 0。您期望会出现一些递归,但事实并非如此。您正在寻找的是累积总和(
SUM OVER
):LAG
looks at one row (per default the one preceding the current row). You create a B that is 0 for every row, then you look atLAG(b)
, but b is 0 in the previous row, too; it is 0 in all rows. You expect some recursion to kick in, but this is not the case.What you are looking for is a cumulative sum (
SUM OVER
):