Re: Windowing functions vs aggregates

From: Tom Lane <tgl(at)sss(dot)pgh(dot)pa(dot)us>
To: Greg Stark <stark(at)enterprisedb(dot)com>
Cc: Teodor Sigaev <teodor(at)sigaev(dot)ru>, Pgsql Hackers <pgsql-hackers(at)postgresql(dot)org>
Subject: Re: Windowing functions vs aggregates
Date: 2009-04-14 13:58:29
Message-ID: 9505.1239717509@sss.pgh.pa.us
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-hackers

Greg Stark <stark(at)enterprisedb(dot)com> writes:
> However, I'm kind of confused by that result. Why does the range
> "between unbounded preceding and current row" seem to be doing the
> average of the whole result set?

That's what it's supposed to do. "Current row" really includes all peers
of the current row in the window frame ordering, and since you didn't
specify any ORDER BY clause, all the rows are peers. If you put in
"order by s" you'll get the result you were expecting:

regression=# select s,(avg(s) OVER (range between unbounded preceding
and current row)) from foo;
s | avg
---+--------------------
1 | 2.5000000000000000
2 | 2.5000000000000000
3 | 2.5000000000000000
4 | 2.5000000000000000
(4 rows)

regression=# select s,(avg(s) OVER (order by s range between unbounded preceding

and current row)) from foo;
s | avg
---+------------------------
1 | 1.00000000000000000000
2 | 1.5000000000000000
3 | 2.0000000000000000
4 | 2.5000000000000000
(4 rows)

I suppose the SQL committee defined it like that to try to reduce the
implementation dependency of the results.

regards, tom lane

In response to

Browse pgsql-hackers by date

  From Date Subject
Next Message Marko Kreen 2009-04-14 14:13:00 Re: Unicode string literals versus the world
Previous Message Tom Lane 2009-04-14 13:35:53 Re: Windowing functions vs aggregates