running total using windows function in sql has sa

2019-05-11 00:12发布

问题:

From every references that I search how to do cumulative sum / running total. they said it's better using windows function, so I did

select grandtotal,sum(grandtotal)over(order by agentname) from call

but I realize that the results are okay as long as the value of each rows are different. Here is the result :

Is There anyway to fix this?

回答1:

You might want to review the documentation on window specifications (which is here). The default is "range between" which defines the range by the values in the row. You want "rows between":

select grandtotal,
       sum(grandtotal) over (order by agentname rows between unbounded preceding and current row)
from call;

Alternatively, you could include an id column in the sort to guarantee uniqueness and not have to deal with the issue of equal key values.