Re: Nice to have features: Percentage function

From: Adrian Klaver <adrian(dot)klaver(at)aklaver(dot)com>
To: Melvin Davidson <melvin6925(at)gmail(dot)com>
Cc: Ron Ben <ronb910(at)walla(dot)co(dot)il>, "pgsql-general(at)postgresql(dot)org" <pgsql-general(at)postgresql(dot)org>
Subject: Re: Nice to have features: Percentage function
Date: 2017-04-16 21:45:42
Message-ID: dba8a5ac-33f6-f2bf-e3fe-fdf5c6be012e@aklaver.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

On 04/16/2017 09:37 AM, Melvin Davidson wrote:
>
>
> On Sun, Apr 16, 2017 at 12:23 PM, Adrian Klaver

>
>
> *Or, you could just as easily compute inline in SQL:
>
> SELECT datname,
> pg_size_pretty(pg_database_size(datname))as size_pretty,
> pg_database_size(datname) as size,
> (SELECT pg_size_pretty (SUM( pg_database_size(datname))::bigint)
> FROM pg_database) AS total,
> ((pg_database_size(datname) / (SELECT SUM(
> pg_database_size(datname))
> FROM pg_database) ) *
> 100)::numeric(6,3) AS pct
> FROM pg_database
> ORDER BY datname;*

Yeah, that is doable but I believe the OP is looking for generic
functions that eliminate the need to write out the math for each query.
A quick and dirty example:

test=# create table percent_test(id int, subtotal numeric, sales_tax
numeric);
CREATE TABLE
test=# insert into percent_test values (1, 128, 8.7), (2, 90, 8.5), (3,
256.35, 8.7), (4, 25.50, 8.5);
INSERT 0 4

test=# select id, subtotal, sales_tax as sales_tax_rate,
percent_of(sales_tax, subtotal)::numeric(7, 2) as tax from percent_test;
id | subtotal | sales_tax_rate | tax
----+----------+----------------+-------
1 | 128 | 8.7 | 11.14
2 | 90 | 8.5 | 7.65
3 | 256.35 | 8.7 | 22.30
4 | 25.50 | 8.5 | 2.17

>
> --
> *Melvin Davidson*
> I reserve the right to fantasize. Whether or not you
> wish to share my fantasy is entirely up to you.

--
Adrian Klaver
adrian(dot)klaver(at)aklaver(dot)com

In response to

Browse pgsql-general by date

  From Date Subject
Next Message Adrian Klaver 2017-04-16 21:47:13 Re: Nice to have features: Percentage function
Previous Message Michael Nolan 2017-04-16 21:33:28 Re: Nice to have features: Percentage function