Search code examples
sqlsql-servert-sqlwindow-functionscumulative-sum

SQL Adding quantity of another column


I need to compute the sum of a column (B) in another column (C), but adding the next value and changing taking into account another column criteria (A), something like this:

enter image description here

Is this possible with a simple SELECT?


Solution

  • In SQL Server, the window function sum() over() should do the trick.

    Note the order by ColB ... This is just a placeholder, I suspect you have another column which would have the proper sequence

    Example

    Select ColA
          ,ColB
          ,ColC = sum(ColB) over (partition by ColA order by ColB rows unbounded preceding )
     From  YourTable