使用SQL在行上的总和,但我们需要停止并在特定条件下启动总和
这是我拥有的数据的示例,也是我想要的 sql 中的输出的示例。
ID | 日期 | 标志 |
---|---|---|
A | 2022-04-05 | 0 |
A | 2022-04-06 | 1 |
A A | 2022-04-07 | 1 |
A A | 2022-04-08 | 1 A |
A | 2022-04-09 | 0 |
2022-04--04--04--04--04-- | 2022-04-10 | 0 |
A | A 11 | 1 |
A | 2022-04-12 | 1 |
A | 2022-04-13 | 1 |
A | 2022-04-14 | 1 |
A | 2022-04-15 | 0 |
A | 2022-04-16 | 0 |
B | 2022-04-05 | 0 |
B | 2022-04-06 | 1 |
B | 2022-04-07 | 1 |
B | 2022-04-08 | 0 |
所需的输出
ID | 日期 | 标志 | |
---|---|---|---|
A | 20222 -04-05 | 0 | 0 |
A | 2022-04-06 | 1 | 1 |
A | 2022-04-07 | 1 | 2 |
A | 2022-04-08 | 1 | 3 a 3 |
a | 2022-04-09 | 0 | 0 |
A | 2022-04-10 | 0 | 0 |
A | 2022-04-11 | 1 | A 1 |
A | 2022-04-12 | 1 | 2 |
A | 2022-04-13 | 1 | 3 |
A | 2022-04-14 | 1 | 4 |
A | 2022-- 04-15 | 0 | 0 |
A | 2022-04-16 | 0 | 0 |
B | 2022-04-05 | 0 | 0 |
B | 2022-04-06 | 1 | 1 |
B | 2022-04-07 | 1 | 2 |
B | 2022-04-08 | 0 | 0 |
基本上,如果flag
的值为1,并继续增加,直到0是0到达,然后继续从1的下一个flag
进行增量,直到下一个0
,等等。
Here is an example of the data I have and the output I want in SQL.
id | date | flag |
---|---|---|
a | 2022-04-05 | 0 |
a | 2022-04-06 | 1 |
a | 2022-04-07 | 1 |
a | 2022-04-08 | 1 |
a | 2022-04-09 | 0 |
a | 2022-04-10 | 0 |
a | 2022-04-11 | 1 |
a | 2022-04-12 | 1 |
a | 2022-04-13 | 1 |
a | 2022-04-14 | 1 |
a | 2022-04-15 | 0 |
a | 2022-04-16 | 0 |
b | 2022-04-05 | 0 |
b | 2022-04-06 | 1 |
b | 2022-04-07 | 1 |
b | 2022-04-08 | 0 |
Desired Output
id | date | flag | count |
---|---|---|---|
a | 2022-04-05 | 0 | 0 |
a | 2022-04-06 | 1 | 1 |
a | 2022-04-07 | 1 | 2 |
a | 2022-04-08 | 1 | 3 |
a | 2022-04-09 | 0 | 0 |
a | 2022-04-10 | 0 | 0 |
a | 2022-04-11 | 1 | 1 |
a | 2022-04-12 | 1 | 2 |
a | 2022-04-13 | 1 | 3 |
a | 2022-04-14 | 1 | 4 |
a | 2022-04-15 | 0 | 0 |
a | 2022-04-16 | 0 | 0 |
b | 2022-04-05 | 0 | 0 |
b | 2022-04-06 | 1 | 1 |
b | 2022-04-07 | 1 | 2 |
b | 2022-04-08 | 0 | 0 |
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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是一个差距和岛屿问题。一种方法使用行数方法的差异:
This is a gaps and islands problem. One approach uses the difference in row numbers method: