Re: computing z-scores

From: "David G(dot) Johnston" <david(dot)g(dot)johnston(at)gmail(dot)com>
To: Martin Mueller <martinmueller(at)northwestern(dot)edu>
Cc: "pgsql-general(at)lists(dot)postgresql(dot)org" <pgsql-general(at)lists(dot)postgresql(dot)org>, "pgsql-hackers(at)postgresql(dot)org" <pgsql-hackers(at)postgresql(dot)org>
Subject: Re: computing z-scores
Date: 2018-05-24 15:22:26
Message-ID: CAKFQuwZP1JiUTL5DqzNMQMOw8cpgCjejo-AjXeLB3RQkb8wCWw@mail.gmail.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general pgsql-hackers

On Thu, May 24, 2018 at 8:15 AM, Martin Mueller <
martinmueller(at)northwestern(dot)edu> wrote:

> You construct a z-score for a set of values by subtracting the average
> from the value and dividing the result by the standard deviation. I know
> how to do this in a two-step procedure. First, I compute the average and
> standard deviation. In a second run I use the formula and apply it to each
> value.
>
> Is there a way of doing this in a single-step procedure or can you chain
> the two parts together in one query? This goes beyond my SQL competence.
>

Window functions provide the easiest means to apply aggregated values to
individual rows.

SELECT v, (v - (AVG(v) OVER ()) / (stddev(v) OVER ())) AS z_v
FROM (
VALUES (1),(2),(3)
) vals (v);

//-1, 0, 1

​https://www.postgresql.org/docs/10/static/tutorial-window.html

David J.

In response to

Responses

Browse pgsql-general by date

  From Date Subject
Next Message Ron 2018-05-24 15:26:44 Re: computing z-scores
Previous Message Maxim Boguk 2018-05-24 15:19:48 Re: found xmin from before relfrozenxid on pg_catalog.pg_authid

Browse pgsql-hackers by date

  From Date Subject
Next Message Ron 2018-05-24 15:26:44 Re: computing z-scores
Previous Message Maxim Boguk 2018-05-24 15:19:48 Re: found xmin from before relfrozenxid on pg_catalog.pg_authid