我有一个表,里面有序列和每一项的计数。我正在尝试一个查询,它在结果中添加一个额外的列,这样在新的列中,每一行/项都将具有其顺序低于该项的所有项计数的总和。
例如:
items [...] seq counts
a [...] 1 1
b [...] 2 1
c [...] 3 8
d [...] 4 2
a [...] 1 1
e [...] null 1结果:
items [...] seq counts sum
a [...] 1 1 (doesnt matter, could be 0 or 1)
b [...] 2 1 1
c [...] 3 8 2
d [...] 4 2 10
a [...] 1 1 (doesnt matter, could be 0 or 1)
e [...] null 1 (doesnt matter)
f [...] 5 10 12我不知道如何用这种情况来总结一些事情。我只知道如何做group by和对一个组中的所有项目求和。子查询对我也不起作用
发布于 2017-01-27 10:39:52
您要查找的是累计总和。您可以使用outer apply来完成此操作
select t.*, t2.sumcounts
from t outer apply
(select sum(t2.counts) as sumcounts
from t t2
where t2.seq < t.seq
) t2;https://stackoverflow.com/questions/41886272
复制相似问题