Skip to content
Advertisement

How to calculate the percentage of salary paid by each account for each employee?

I need to find the percentage of an employee’s salary that is paid by each account.

For example.. I need to find a way to sum the amounts of each employee and then divide each amount by that total.

I have read up about the ratio to report function in sql but it does not solve my problem as it sums every employee’s salary and then gives a % based upon that total.

I also tried to do a separate subquery where I do the simple math (x/(x+y)*100) but I don’t want to have to Group By the amount, as that increases the line output dramatically.

I would simply like to have a % of total salary for each employee/account combination. Thanks!

Advertisement

Answer

From what I understand, you are probably looking for the analytic version of ratio_to_report(), which is otherwise, indeed, the correct solution. Something like this (note that I include the test data in a WITH clause at the top; that is not part of the query, it should be removed when you apply the solution to your real-life data).

(As you can see, I did not order the output; you can, if you need to.)

Notice the analytic clause, over (partition by employee); I believe that’s the part you were missing.

I don’t know how that fits with the rest of your code, where you do a lot of things that don’t seem related to the question you asked.

Also, I hope your amounts are numbers, not strings. (Not sure about the dollar symbol in front of each amount…)

You didn’t state how you want the percentages to be formatted. Without any formatting, you will get something like 0.3333333333 for 33 1/3 % (one-third). You may need to multiply by 100, cut the decimals off at two or three digits, add a percent sign, etc. – all of that can be done in the SELECT clause of the main query. However, that should only be done if this is the final output that goes straight to a human readable report; if the values are used in further processing (computations), it is best to leave them exactly as they are.

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