Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PostgreSQL - Determining the Percentage of a Total

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?

like image 333
Marián Zeke Šedaj Avatar asked Oct 25 '12 10:10

Marián Zeke Šedaj


People also ask

How do I get the percentage of total in PostgreSQL?

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.

How do I calculate SQL Data percentage?

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.

How do I find the percentage between two columns?

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.


1 Answers

You could use sum with an over clause:

SELECT  100.0 * number / sum(number) over () as perc
FROM    mytable;

Example at SQL Fiddle.

like image 156
Andomar Avatar answered Oct 03 '22 20:10

Andomar