Received: from malur.postgresql.org ([217.196.149.56]) by arkaria.postgresql.org with esmtps (TLS1.3:ECDHE_RSA_AES_256_GCM_SHA384:256) (Exim 4.92) (envelope-from ) id 1orgYh-000537-4S for pgsql-general@arkaria.postgresql.org; Sun, 06 Nov 2022 14:23:35 +0000 Received: from localhost ([127.0.0.1] helo=malur.postgresql.org) by malur.postgresql.org with esmtp (Exim 4.92) (envelope-from ) id 1orgYf-0002JO-0n for pgsql-general@arkaria.postgresql.org; Sun, 06 Nov 2022 14:23:33 +0000 Received: from makus.postgresql.org ([2001:4800:3e1:1::229]) by malur.postgresql.org with esmtps (TLS1.3:ECDHE_RSA_AES_256_GCM_SHA384:256) (Exim 4.92) (envelope-from ) id 1orgYe-0002JE-MD for pgsql-general@lists.postgresql.org; Sun, 06 Nov 2022 14:23:32 +0000 Received: from mout-u-204.mailbox.org ([2001:67c:2050:101:465::204]) by makus.postgresql.org with esmtps (TLS1.3:ECDHE_RSA_AES_256_GCM_SHA384:256) (Exim 4.92) (envelope-from ) id 1orgYZ-0006oI-NS for pgsql-general@lists.postgresql.org; Sun, 06 Nov 2022 14:23:31 +0000 Received: from smtp2.mailbox.org (smtp2.mailbox.org [10.196.197.2]) (using TLSv1.3 with cipher TLS_AES_256_GCM_SHA384 (256/256 bits) key-exchange ECDHE (P-384) server-signature RSA-PSS (4096 bits) server-digest SHA256) (No client certificate requested) by mout-u-204.mailbox.org (Postfix) with ESMTPS id 4N4xRX6lDtz9sQL; Sun, 6 Nov 2022 15:23:20 +0100 (CET) Date: Sun, 6 Nov 2022 15:23:19 +0100 (CET) From: Erik Wienhold To: Rafal Pietrak , pgsql-general@lists.postgresql.org Message-ID: <251756722.142989.1667744599679@office.mailbox.org> In-Reply-To: References: Subject: Re: an difficult SQL MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: quoted-printable X-Priority: 3 Importance: Normal List-Id: List-Help: List-Subscribe: List-Post: List-Owner: List-Archive: Archived-At: Precedence: bulk > On 06/11/2022 13:48 CET Rafal Pietrak wrote: > > W dniu 5.11.2022 o=C2=A019:05, Thiemo Kellner pisze: > > > > You first could select the three users with the most recent entries wit= h > > 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 ar= e 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