Rows From but with Subqueries (or a cleaner non-array-using alternative)?

From: "David G(dot) Johnston" <david(dot)g(dot)johnston(at)gmail(dot)com>
To: "pgsql-generallists(dot)postgresql(dot)org" <pgsql-general(at)lists(dot)postgresql(dot)org>
Subject: Rows From but with Subqueries (or a cleaner non-array-using alternative)?
Date: 2022-02-15 00:06:16
Message-ID: CAKFQuwaWSDRGXBiv-FrsomDiPFeUTYov-KRXevNnqHz62335GA@mail.gmail.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

Hi!

In the following query I ended up using unnest(array(subquery)) in order to
pair up the rows with starting indices and the rows with ending indices.
This is exactly what "FROM ROWS FROM (function)" would do but alas I have a
subquery. In the target list I have to use scalar subqueries so doing this
directly there is a no-go. Hence the array intermediary. Am I
missing/forgetting some feature that can do this without the intermediate
array?

Thanks!

David J.

WITH vals (i,v) AS (VALUES
(0,1),(1,0),(2,0),(3,1),(4,0),(5,0),(6,1),(7,1),(8,0),(9,1)),
boundaries AS (SELECT *,
CASE WHEN COALESCE(LAG(v) OVER (ORDER BY i), -1) <> 0 AND v=0 THEN 'Start'
ELSE NULL END AS start_tag,
CASE WHEN COALESCE(LEAD(v) OVER (ORDER BY i), -1) <> 0 AND v=0 THEN 'End'
ELSE NULL END AS end_tag
FROM vals
),
frames AS (SELECT
UNNEST(ARRAY((SELECT i FROM boundaries WHERE start_tag = 'Start' ORDER BY
i))) AS start_at,
UNNEST(ARRAY((SELECT i FROM boundaries WHERE end_tag = 'End' ORDER BY i)))
AS end_at
)
SELECT vals.i, vals.v,
frames.start_at AS group_index,
row_number() OVER (PARTITION BY frames.start_at ORDER BY vals.i)
FROM vals
JOIN frames ON vals.i BETWEEN frames.start_at AND frames.end_at

Responses

Browse pgsql-general by date

  From Date Subject
Next Message A Shaposhnikov 2022-02-15 00:06:34 Re: increasing effective_cache_size slows down join queries by a factor of 4000x
Previous Message Alan Hodgson 2022-02-14 21:44:45 Re: Moving the master to a new server