pg.ddx.io  pgsql-general@postgresql.org mailing list archive  
help / color / mirror / Atom feed
From: Erik Wienhold <ewie@ewie.name>
To: Rafal Pietrak <rafal@ztk-rp.eu>
To: pgsql-general@lists.postgresql.org
Subject: Re: an difficult SQL
Date: Sun, 6 Nov 2022 15:23:19 +0100 (CET)
Message-ID: <251756722.142989.1667744599679@office.mailbox.org> (raw)
In-Reply-To: <ad4613e1-4e41-c56a-70dd-1f53bb6b9393@ztk-rp.eu>
References: <d0c374e1-4e50-6b1f-21f0-b16564aa934b@ztk-rp.eu>
	<a5dbd00f-525d-1e06-0a87-dc629ab84559@gelassene-pferde.biz>
	<ad4613e1-4e41-c56a-70dd-1f53bb6b9393@ztk-rp.eu>

> On 06/11/2022 13:48 CET Rafal Pietrak <rafal@ztk-rp.eu> wrote:
>
> W dniu 5.11.2022 o 19:05, Thiemo Kellner pisze:
> >
> > You first could select the three users with the most recent entries with
> > a windowing function
> > (https://www.postgresql.org/docs/15/sql-expressions.html#SYNTAX-WINDOW-FUNCTIONS)
>
> surely I'm missing something crucial here:
> select row_number() over w,* from eventlog where row_number() over w < 5
>   window w as (partition by user);
> ERROR:  window functions are not allowed in WHERE
>
> So I'm unable to pick a limited number of rows within the user
> "group-window" ranges.
>
> Without that, I cannot proceed.
>
> Any suggestions?

Windows functions are only permitted in SELECT and ORDER BY because they are
executed after WHERE, GROUP BY, and HAVING[1].

You need a derived table to filter on row_number:

    with
    ranked as (
        select *, row_number() over w
        from eventlog
        window w as (partition by user)
    )
    select *
    from ranked
    where row_number < 5;

[1] https://www.postgresql.org/docs/15/tutorial-window.html

--
Erik





view thread (5+ messages)  latest in thread

Message-ID: <251756722.142989.1667744599679@office.mailbox.org>
Permalink:  ../251756722.142989.1667744599679@office.mailbox.org/
Also on:    postgresql.org/message-id/251756722.142989.1667744599679@office.mailbox.org

 · 

reply

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Reply to all the recipients from your mail client; the link fills in
  the headers below: reply via email
  Some clients, webmail especially, drop In-Reply-To and References from
  a link, and the reply then starts a new thread: use the mbox below.

  To: pgsql-general@postgresql.org
  Cc: ewie@ewie.name, rafal@ztk-rp.eu
  Subject: Re: an difficult SQL
  In-Reply-To: <251756722.142989.1667744599679@office.mailbox.org>
  References: <d0c374e1-4e50-6b1f-21f0-b16564aa934b@ztk-rp.eu> <a5dbd00f-525d-1e06-0a87-dc629ab84559@gelassene-pferde.biz> <ad4613e1-4e41-c56a-70dd-1f53bb6b9393@ztk-rp.eu> <251756722.142989.1667744599679@office.mailbox.org>

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

This inbox is served by DDX for PostgreSQL; see mirroring instructions
for how to clone and mirror all data and code used for this inbox