I will need your help with this one. I want to normalize numbers within groups. Say I have this dataset:
A B C
-------
0 1 3
1 1 0
1 1 2
1 1 4
1 2 1
1 2 1
I want to group these rows by A and B, then normalize the values of C within its group, i.e. summing up all C's of the group and then dividing each C by that sum. In the above example, I would expect this result:
A B C
---------
0 1 1 // sum of C's in group is 1, 1/1=1
1 1 0 // sum of C's in group is 6, 0/6=0
1 1 1/3 // ...
1 1 2/3 // ...
1 2 1/2 // sum of C's in group is 2, 1/2=1/2
1 2 1/2 // ...
Division by zero can be handled separately. How to do this using SQL (or PSQL, if that helps)? I can think of ways to do this in principle, but I always end up with deeply nested SELECTs, which I want to avoid.
Thanks in advance!