0

I'd like to do cumulative sum of the column SubTotal to get a cumulative RunningTotal column. But I noticed that if rows have the same values, the cumulative sum doesn't work. e.g. In the below example, the row 5 and row 6 have the same SubTotal value of 838.9178. Because of that, the RunningTotal column doesn't sum up for row 5 and row 6.

example

How can i fix this issue? I expect to get the results like below:

expected

Below please find my query. Many thanks in advance!

select YEAR(OrderDate) as FiscalYear,
       REPLACE(CONVERT(varchar(12), OrderDate,1), ' ', '-') as OrderDate,
       SubTotal,
       SUM (SubTotal) OVER (partition by YEAR(OrderDate) ORDER BY OrderDate,SubTotal ) AS RunningTotal
from Sales.SalesOrderHeader
where YEAR(OrderDate)=2012 or YEAR(OrderDate)=2013
order by YEAR(OrderDate),OrderDate;
1
  • Actually I believe you'd want the 2nd cell to stay 2894.3139 but the first one to be 2055.3961, but I think it's going to have issues because the rows are identical and it wouldn't know which would come first so it adds both values and gives the same cumulative for both. Commented Jan 29, 2020 at 20:19

1 Answer 1

3

You need a row windowing clause or a stable sort. Try this:

   SUM(SubTotal) OVER (partition by YEAR(OrderDate) ORDER BY OrderDate ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS RunningTotal

Or, if you have a unique id (UniqueId for example) on the row:

   SUM(SubTotal) OVER (partition by YEAR(OrderDate) ORDER BY OrderDate, UniqueId) AS RunningTotal

The issue is that the default windowing clause uses RANGE BETWEEN, which is not what you want.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.