Re: an difficult SQL

From: Rafal Pietrak <rafal(at)ztk-rp(dot)eu>
To: pgsql-general(at)lists(dot)postgresql(dot)org
Subject: Re: an difficult SQL
Date: 2022-11-06 15:48:59
Message-ID: f8bb7ecf-11bd-a271-a74d-9fd3032eb912@ztk-rp.eu
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

Great, with a little tweaking (to get the remaining rows ordered
correctly), this did the job.

Thank you Erik.

BR

-R

W dniu 6.11.2022 o 15:23, Erik Wienhold pisze:
>> On 06/11/2022 13:48 CET Rafal Pietrak <rafal(at)ztk-rp(dot)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
>
>

In response to

Browse pgsql-general by date

  From Date Subject
Next Message Siddharth Jain 2022-11-06 19:05:39 Re: Some questions about Postgres
Previous Message Tom Lane 2022-11-06 14:48:32 Re: server process (PID 2964738) was terminated by signal 11: Segmentation fault