First Last Non Null Per Group

Get the first and last non null values per group using window functions with ignore nulls framing.

SqlData Fetching

Code

sqlsnippet
14 lines
SELECT DISTINCT
  partition_key,
  FIRST_VALUE(value) IGNORE NULLS OVER (
    PARTITION BY partition_key
    ORDER BY sort_key
    ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING
  ) AS first_non_null,
  LAST_VALUE(value) IGNORE NULLS OVER (
    PARTITION BY partition_key
    ORDER BY sort_key
    ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING
  ) AS last_non_null
FROM observations
ORDER BY partition_key;

What the code does

At its core this is a single SELECT statement against observations.

Breaking the statements into their working parts: a window function (OVER (…)) computing values across rows without collapsing them; an ORDER BY that fixes the output order; a DISTINCT qualifier that collapses duplicate rows.

What to watch for

  • Window functions evaluate after WHERE/GROUP BY, so filtering on their output in the same-level WHERE will not work — use an outer query or a CTE.

Applying it

Run the statement against the observations table.

Interactive Tools for This Topic

FAQ

What are the relations in play here?
The references are `observations`.