SQL 在同一行上迭代

发布于 2025-01-10 09:05:41 字数 3762 浏览 0 评论 0原文

我正在寻找 SQL 代码来执行此操作:

tab_input

IDDatA
a73
a64
a51
b25
b39
b12

我想计算一个新列 B[i] = A[i] + B [i-1],但当 ID 更改时,字段 B 会重置

tab_output

IDDatAB
a511
a645
a738
b122
b257
b3916

我尝试了以下方法:

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
;

但它不起作用,结果是

IDDatAB
a511
a644
a733
b122
b255
b399

我认为它是添加到所有 0 的值并且不会更新 B 的值

我非常感谢您的帮助!

I am looking for SQL code to do this:

tab_input

IDDatA
a73
a64
a51
b25
b39
b12

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

IDDatAB
a511
a645
a738
b122
b257
b3916

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

IDDatAB
a511
a644
a733
b122
b255
b399

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

安人多梦 2025-01-17 09:05:41

LAG 查看一行(默认情况下是当前行之前的一行)。您为每一行创建一个值为 0 的 B,然后查看 LAG(b),但前一行中的 b 也为 0;所有行都是 0。您期望会出现一些递归,但事实并非如此。

您正在寻找的是累积总和(SUM OVER):

SELECT id, dat, a, SUM(a) OVER (PARTITION BY id ORDER BY dat) AS b
FROM tab_input
ORDER BY id, dat;

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 at LAG(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):

SELECT id, dat, a, SUM(a) OVER (PARTITION BY id ORDER BY dat) AS b
FROM tab_input
ORDER BY id, dat;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文