I have a table
ID | NUMBER
------|----------
1 | 102
2 | 145
3 | 512
4 | 231
5 | 94
and I want to sum all 'NUMBER' and return a % value from total to each row. Result should look like this:
ID | NUMBER | PERC
------|--------------|-------
1 | 102 | 9.4
2 | 145 | 13.4
3 | 512 | 47.2
4 | 231 | 21.3
5 | 94 | 8.7
So far, I have something like:
SELECT (number/sum(number)*100) AS perc
FROM mytable;
but as you know for sure, that 'number' must appear in GROUP BY or aggregate function so I can't use it. How to do that?
Calculating the “percentage of the total” for each row with Postgres can be done with a window function: SELECT *, (value / SUM(value) OVER ()) AS "% of total" FROM transactions WHERE quarter = '2015-03-31' and company_id = 1; We're using “OVER ()”, which means the sum over all rows returned by the where clause.
There is no built-in operator that calculates percentages in SQL Server. You have to rely on basic arithmetic operations i.e. (number1/number2 x 100) to find percentages in SQL Server.
If you want to find the percentage of two cells in Microsoft Excel, Simply select an empty cell, where you want to display the percentage of the two cells. For example, I want to print out the percentage of C2 and C3, so the formulae will be: =C2/C3, in an empty cell C4.
You could use sum
with an over
clause:
SELECT 100.0 * number / sum(number) over () as perc
FROM mytable;
Example at SQL Fiddle.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With