Re: [SQL] Percentages?

From: Nuchanard Chiannilkulchai <nuch(at)valigene(dot)com>
To: pgsql-sql(at)postgresql(dot)org
Subject: Re: [SQL] Percentages?
Date: 1999-04-27 08:20:03
Message-ID: 37257333.522DF88A@valigene.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-sql

Chris Bitmead wrote:

> How to calculate percentages? What is the correct SQL?
>
> CREATE TABLE poll (candidate text, votes int4);
>
> I want to do something like (this is wrong)...
> SELECT candidate, votes, (votes / sum(votes)) * 100) AS percent FROM
> poll;
>
> Fred Smith | 500 | 25
> Bill Bloggs | 1000 | 50
> Jim Jones | 500 | 25
>
> --
> Chris Bitmead
> http://www.bigfoot.com/~chris.bitmead
> mailto:chris(dot)bitmead(at)bigfoot(dot)com

I always solve by a temporary table

select sum(votes) as sumvotes into tmp from poll;
SELECT candidate, votes, (float4(votes)/float4(sumvotes))*100
as percent from poll, tmp;
candidate|votes| percent
---------+-----+----------------
Fred | 500|23.8095238804817
Bill | 1000|47.6190477609634
James | 600| 28.571429848671
(3 rows)

The problem is now cutting to only to 2 decimal point (ie: 23.80,
47.61, 28.57)
and we need some further help.

Nuch

In response to

Responses

Browse pgsql-sql by date

  From Date Subject
Next Message José Soares 1999-04-27 12:50:20 Re: [SQL] Percentages?
Previous Message Nuchanard Chiannilkulchai 1999-04-27 08:15:35 Re: [SQL] substring