Re: Calculating Percentages

From: Christoph Haller <ch(at)rodos(dot)fzk(dot)de>
To: pgsql-sql(at)postgresql(dot)org
Cc: dsiegal(at)brave(dot)cs(dot)uml(dot)edu
Subject: Re: Calculating Percentages
Date: 2003-05-15 09:04:50
Message-ID: 3EC35832.8BA90263@rodos.fzk.de
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-sql

>
> SELECT nationality, (COUNT(*)*100/total_members) as percentage
> FROM member,
> (SELECT COUNT(*) as total_members FROM members) tot_mem
> GROUP BY nationality
> ORDER BY nationality
>
You'll have to GROUP BY nationality, total_members

Remember COUNT returns bigint, so percentage is the
result of an integer division. To obtain floating point results use
(COUNT(*)*100.0/total_members)

> > If I were to do:
>
> > SELECT nationality, ((COUNT(*) * 100)/(select count(*) from member))
as
> > percentage FROM member GROUP BY nationality ORDER BY nationality;
>
> > would this repeatedly execute the inner query over and over?
>
> No, it'd do it just once, because the sub-select has no dependency on
> the outer select. (If the sub-select used any variables from the
outer
> level, then it'd have to be done over at each outer row.)
>
Really nice piece of analyzer.

Regards, Christoph

Responses

Browse pgsql-sql by date

  From Date Subject
Next Message David W Noon 2003-05-15 11:39:38 Re: Left Join 3 tables
Previous Message Luis Sousa 2003-05-15 08:45:51 Re: I need help with a rule to relocate duplicate records