I’m using an aggregate function with the OVER clause in PostgreSQL 9.1 and I want to return just the last row for each window. The last_value() window function sounds like it might do what I want – but it doesn’t. It returns a row for each row in the window, whereas I want just one row per window
A simplified example:
SELECT a, some_func_like_last_value(b) OVER (PARTITION BY a ORDER BY b)
FROM
(
SELECT 1 AS a, 'do not want this' AS b
UNION SELECT 1, 'just want this'
) sub
I want this to return one row:
1, 'just want this'
DISTINCTplus window functionAdd a
DISTINCTclause:More about
DISTINCT:Simpler and faster with
DISTINCT ONPostgreSQL also has this extension of the SQL standard:
More about
DISTINCT ONand possibly faster alternatives:Simple case with plain aggregate
If your case is actually as simple as your demo (and you don’t need additional columns from that last row), a plain aggregate function will be simpler: