i有以下结构的表
| id | a | b |
| 1 | 1 | 1 |
| 2 | 1 | 5 |
| 3 | 2 | 2 |
| 4 | 2 | 3 |
| 5 | 2 | 5 |
| 6 | 1 | 3 |
| 7 | 1 | 7 |
| 8 | 3 | 1 |
| 9 | 2 | 0 |
| 10 | 4 | 8 |
并且需要计算列" A"中每个组中" B"列中的总和,但考虑到行的顺序,即首先我们应该为a == 1
添加1 + 5
(id
S 1和2),然后,我们将为a = 2
添加2 + 3 + 5
(id
S 3、4、5),等等。
因此,在结果中我需要像这样的表格
| a | sum(b) |
| 1 | 6 |
| 2 | 10 |
| 1 | 10 |
| 3 | 1 |
| 2 | 0 |
| 4 | 8 |
请帮助编写SQL查询来执行此操作。
select a,sum(b)
from (select *
,row_number () over (order by id) as rn
,row_number () over (partition by a order by id) as rnp
from t
) t
group by a,rn - rnp
order by min(id)
;
P.S。
我不是要指望ID是连续的