-3

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?

Charlieface
  • 52,284
  • 6
  • 19
  • 43
Mazinger
  • 633
  • 1
  • 6
  • 12
  • 2
    Is it possible? Probably. If you provide a clear description of the logic to be used rather than some unclear "like this" and "taking into account another column" phrases, someone might be able to help. – SMor Mar 21 '22 at 19:43
  • You want to get a running total of column B in column C for each distinct value in column A, correct? If so: `=SUMIF(A$1:A1,A1, $B$1:$B$8)` and copy down. – JNevill Mar 21 '22 at 19:43

1 Answers1

2

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
John Cappelletti
  • 79,615
  • 7
  • 44
  • 66
  • John, your solution almost work except in a certain case. When COLB repeats, COLC has always the same result, the total sum. For example, imagine COLB has 20, 40, 40 values, then COLC shows 20, 100, 100, when it should be: 20, 60, 100 – Mazinger Mar 21 '22 at 23:25
  • @Mazinger Just added tje rows unbounded preceding ... As Charilieface suggested. – John Cappelletti Mar 22 '22 at 02:58
  • @Mazinger Here is a working example https://dbfiddle.uk/?rdbms=sqlserver_2016&fiddle=193cde04d266f9ad5a1eeee42ae18212 – John Cappelletti Mar 22 '22 at 02:59
  • Now it totally works! That last tip do the trick. – Mazinger Mar 22 '22 at 11:50