Skip to content
Advertisement

Divide the column by the sum grouped by another column

I have a table like this

and I would like to divide the frequency by the sum of frequency grouped by the source. Therefore, I am looking for a table like

Is there any way to do this in a single sql query?

Advertisement

Answer

You can use SUM() window function.

If you want a numerical result:

Depending on your database, if it performs integer division between integers, you may need to multiply by 1.0:

If you want the result as a string you can do it with concatenation:

I used CONCAT(), but if your database does not support it use its concatenation operator and also you may need to convert the integer values to strings.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement