Italo Rodrigo
Italo Rodrigo

Reputation: 1785

Is possible to get the percentage value on query using count and group by?

I have a Query:

select no_tipo_origem, 
       count(*) total 
from table 
group by no_tipo_origem

The result is:

tipo 1 |  25
tipo 2 | 133
tipo 3 |  48

I need to calculate the percentage like this:

tipo 1 |  25 | 12.1
tipo 2 | 133 | 64.5
tipo 3 |  48 | 23.3

Upvotes: 1

Views: 97

Answers (1)

forpas
forpas

Reputation: 164099

Divide each total with the sum of all totals which you can get with SUM() window function:

select no_tipo_origem, 
       count(*) total,
       round(100.0 * count(*) / sum(count(*)) over (), 1) percentage 
from tablename 
group by no_tipo_origem
order by no_tipo_origem

See a simplified demo.

Upvotes: 1

Related Questions