Re: [SQL] Percentages?

From: José Soares <jose(at)sferacarta(dot)com>
To: Nuchanard Chiannilkulchai <nuch(at)valigene(dot)com>
Cc: pgsql-sql(at)postgresql(dot)org
Subject: Re: [SQL] Percentages?
Date: 1999-04-27 12:50:20
Message-ID: 3725B28C.AE3D4406@sferacarta.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-sql

Nuchanard Chiannilkulchai ha scritto:

> 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 v6.5 you can use decimal type.
otherwise try this:

select candidate, votes, substr(cast(percents as text),1,position('.' in
cast(pe
rcents as text))) ||
substr(cast(percents as text),position('.' in cast(percents as text)) + 1,
2) as
percent from test;
candidate|votes|percent
---------+-----+-------
Fred | 500| 23.80
Bill | 1000| 47.61
James | 600| 28.57
(3 rows)

or this ...

select candidate, votes, format(percents,'###,##') from test;

candidate|votes|format
---------+-----+------
Fred | 500| 23,80
Bill | 1000| 47,61
James | 600| 28,57
(3 rows)

-- NB: Here in Italy we use comma instead of decimal point.

Attached file contains:
format() function
text(float8) function (to cast percents to text)

José

Attachment Content-Type Size
format.sql text/plain 3.4 KB
text_float.sql text/plain 581 bytes

In response to

Browse pgsql-sql by date

  From Date Subject
Next Message José Soares 1999-04-27 13:01:32 Re: [SQL] substring
Previous Message Nuchanard Chiannilkulchai 1999-04-27 08:20:03 Re: [SQL] Percentages?