Re: [GENERAL] Calcuate percentage.

From: Clark Evans <clark(dot)evans(at)manhattanproject(dot)com>
To: Sze Yuen Wong <swong_(at)yahoo(dot)com>
Cc: pgsql-general(at)hub(dot)org
Subject: Re: [GENERAL] Calcuate percentage.
Date: 1999-03-10 00:41:59
Message-ID: 36E5BFD7.7270108E@manhattanproject.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

It's crude and not very efficient, but here is a solution:

CREATE TABLE temp ( var INT2 );
INSERT INTO temp VALUES (1);
etc.

CREATE FUNCTION temp_row_count() RETURNS FLOAT AS
'SELECT COUNT(*)::FLOAT AS result FROM temp'
LANGUAGE 'sql';

SELECT var, COUNT(*)::FLOAT / temp_row_count() AS pct
FROM temp GROUP BY var;

Hope this helps,

Clark

P.S. In oracle, I'd use a sub-query:

SELECT var, COUNT(*) / total_count
FROM temp,
( SELECT COUNT(*) AS total_count
FROM temp
)
GROUP BY var;

Sze Yuen Wong wrote:
>
> Hi,
>
> I need to calcuate the percentage from my table:
>
> var1
> ------
> 1
> 1
> 1
> 2
> 2
> 3
>
> Desire result:
>
> var1 | percentage
> ----------------------------
> 1 | 50%
> 2 | 33%
> 3 | 17%
>
> ===============================
>
> Any clue?
>
> Please help.
>
> Sze Wong
>
> _________________________________________________________
> DO YOU YAHOO!?
> Get your free @yahoo.com address at http://mail.yahoo.com

In response to

Responses

Browse pgsql-general by date

  From Date Subject
Next Message M Simms 1999-03-10 00:58:46 Database out of sync
Previous Message Naceur 1999-03-09 21:21:05 Postgres tutorial examples !