My dataset looks like this:
COLA | COLB
Name1 | 218
Name2 | 157
Name3 | 134
Name4 | 121
I need this output:
COLA | COLB| COLC
Name1 | 218 | 0.34
Name2 | 157 | 0.60
Name3 | 134 | 0.71
Name4 | 121 | 1
My SQL looks like this so far:
SELECT COLA, COLB, COLB/SUM(COLB) FROM #MyTempTable
Two problems with this SQL. One, COLC is 0 everytime and I don’t understand that. Two, even if it did result in the % it’s not a cumulative %.
I’ve seen some similar threads on StackOverflow, but I wasn’t able to make the answers from those threads work in my exact scenario.
Thanks in advance for any suggestions!
I think you’re looking for something like this, though your example calculations may be off a little:
EDIT: I’ve added rounding.
This gives us the following output:
The reason that your results are 0 (or 1) is because you are dividing ints by ints, thus giving you an int (see Datatype precedence).
UPDATE:
I should add that this uses a “triangular join” to get the running total (
WHERE COLA <= a.COLA). Depending upon your SQL Server version, you may compare this to other options if performance becomes a concern.