sqlcmd.net validated sql reference
advanced windowing MySQL MariaDB SQL Server PostgreSQL SQLite

Get The Last Value In A Window Partition

Use LAST_VALUE with an explicit full-partition frame to compare each row with the final row in its group.

Docker-validated Not currently validation-green

Show every ticket event with the final status for that ticket

The full-partition frame lets every row see the final row in its ticket partition, not just rows up to the current event.

Rows loaded before the example query runs.
Setup
CREATE TABLE ticket_events (ticket_id INT, step_no INT, status VARCHAR(20));

INSERT INTO
  ticket_events
VALUES
  (1, 1, 'open'),
  (1, 2, 'waiting'),
  (1, 3, 'closed'),
  (2, 1, 'open'),
  (2, 2, 'escalated');
Shared across supported engines.
SQL
SELECT
  ticket_id,
  step_no,
  status,
  LAST_VALUE (status) OVER (
    PARTITION BY
      ticket_id
    ORDER BY
      step_no ROWS BETWEEN UNBOUNDED PRECEDING
      AND UNBOUNDED FOLLOWING
  ) AS final_status
FROM
  ticket_events
ORDER BY
  ticket_id,
  step_no;
Returned rows for the shared example.
ticket_idstep_nostatusfinal_status
11openclosed
12waitingclosed
13closedclosed
21openescalated
22escalatedescalated

The explicit frame makes the result consistent across engines.

Where this command helps.

  • showing each row beside the final status in its group
  • comparing each event with the last event in the same sequence

What the command is doing.

LAST_VALUE returns the value from the last row in the current window frame. The frame detail is important: with the default frame, many engines stop the frame at the current row, making LAST_VALUE return the current row instead of the partition's final row. Add ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING when you want the true last row in each partition.