使用SQL在行上的总和,但我们需要停止并在特定条件下启动总和

发布于 2025-02-13 14:23:10 字数 2458 浏览 1 评论 0原文

这是我拥有的数据的示例,也是我想要的 sql 中的输出的示例。

ID日期标志
A2022-04-050
A2022-04-061
A A2022-04-071
A A2022-04-081 A
A2022-04-090
2022-04--04--04--04--04--2022-04-100
AA 111
A2022-04-121
A2022-04-131
A2022-04-141
A2022-04-150
A2022-04-160
B2022-04-050
B2022-04-061
B2022-04-071
B2022-04-080

所需的输出

ID日期标志
A20222 -04-0500
A2022-04-0611
A2022-04-0712
A2022-04-0813 a 3
a2022-04-0900
A2022-04-1000
A2022-04-111A 1
A2022-04-1212
A2022-04-1313
A2022-04-1414
A2022-- 04-1500
A2022-04-1600
B2022-04-0500
B2022-04-0611
B2022-04-0712
B2022-04-0800

基本上,如果flag的值为1,并继续增加,直到0是0到达,然后继续从1的下一个flag进行增量,直到下一个0,等等。

Here is an example of the data I have and the output I want in SQL.

iddateflag
a2022-04-050
a2022-04-061
a2022-04-071
a2022-04-081
a2022-04-090
a2022-04-100
a2022-04-111
a2022-04-121
a2022-04-131
a2022-04-141
a2022-04-150
a2022-04-160
b2022-04-050
b2022-04-061
b2022-04-071
b2022-04-080

Desired Output

iddateflagcount
a2022-04-0500
a2022-04-0611
a2022-04-0712
a2022-04-0813
a2022-04-0900
a2022-04-1000
a2022-04-1111
a2022-04-1212
a2022-04-1313
a2022-04-1414
a2022-04-1500
a2022-04-1600
b2022-04-0500
b2022-04-0611
b2022-04-0712
b2022-04-0800

Basically the increment should start if the value of flag is 1 and continue incrementing until a flag of 0 is reached, then continue incrementing from the next flag of 1 until the next 0, and so on.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(1

云醉月微眠 2025-02-20 14:23:10

这是一个差距和岛屿问题。一种方法使用行数方法的差异:

WITH cte AS (
    SELECT *, ROW_NUMBER() OVER (PARTITION BY id ORDER BY date) rn1,
              ROW_NUMBER() OVER (PARTITION BY id, flag ORDER BY date) rn2
    FROM yourTable
)

SELECT id, date, flag,
       SUM(flag) OVER (PARTITION BY id, flag, rn1 - rn2 ORDER BY date) AS count
FROM cte
ORDER BY id, date;

This is a gaps and islands problem. One approach uses the difference in row numbers method:

WITH cte AS (
    SELECT *, ROW_NUMBER() OVER (PARTITION BY id ORDER BY date) rn1,
              ROW_NUMBER() OVER (PARTITION BY id, flag ORDER BY date) rn2
    FROM yourTable
)

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