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 1kDpnt-0005cw-St for pgsql-general@arkaria.postgresql.org; Thu, 03 Sep 2020 14:01:29 +0000 Received: from localhost ([127.0.0.1] helo=malur.postgresql.org) by malur.postgresql.org with esmtp (Exim 4.92) (envelope-from ) id 1kDpns-0002Bk-RA for pgsql-general@arkaria.postgresql.org; Thu, 03 Sep 2020 14:01:28 +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 1kDpns-0002Ba-II for pgsql-general@lists.postgresql.org; Thu, 03 Sep 2020 14:01:28 +0000 Received: from sss.pgh.pa.us ([66.207.139.130]) by makus.postgresql.org with esmtps (TLS1.3:ECDHE_RSA_AES_256_GCM_SHA384:256) (Exim 4.92) (envelope-from ) id 1kDpno-0008EM-Mz for pgsql-general@postgresql.org; Thu, 03 Sep 2020 14:01:27 +0000 Received: from sss1.sss.pgh.pa.us (localhost [127.0.0.1]) by sss.pgh.pa.us (8.15.2/8.15.2) with ESMTP id 083E1MlY583851; Thu, 3 Sep 2020 10:01:22 -0400 From: Tom Lane To: Alban Hertroys cc: Postgres General Subject: Re: How to enumerate partitions from a window function? In-reply-to: References: Comments: In-reply-to Alban Hertroys message dated "Thu, 03 Sep 2020 15:12:55 +0200" MIME-Version: 1.0 Content-Type: text/plain; charset="us-ascii" Content-ID: <583849.1599141682.1@sss.pgh.pa.us> Date: Thu, 03 Sep 2020 10:01:22 -0400 Message-ID: <583850.1599141682@sss.pgh.pa.us> List-Id: List-Help: List-Subscribe: List-Post: List-Owner: List-Archive: Precedence: bulk Alban Hertroys writes: > As stated above, I want to enumerate the runs, starting at 1 and > incrementing by 1 every time a partition from the 'run' window closes, > Is there a way to achieve this through window functions, or do we need to > wrap the thing in a subquery to achieve this? I think this'll work: select datetime, property_A, property_B , first_value(datetime)::time over run as swap_time , dense_rank() over (order by property_A, property_B) , value from process_data window run as (partition by property_A, property_B order by datetime) ; You can't do it with a window function over the "run" window because no window function ever looks outside the current partition. But that's easy to fix by using a different window definition. The planner is smart enough to see that these windows are compatible and only need one sort to be performed. regards, tom lane