There are popular case, where is needed to select a row with max value (or min or whatever else aggregate function result) from a table. My case is more complex - it adds JOIN
into the picture.
Here is an example:
CREATE TABLE spacecraft (
id serial PRIMARY KEY,
name text NOT NULL
);
CREATE TABLE launch (
id serial PRIMARY KEY,
spacecraft_id int REFERENCES spacecraft(id) NOT NULL,
started timestamptz NOT NULL,
success bool NOT NULL
);
INSERT INTO spacecraft (id, name) VALUES
(1, 'Bebop'),
(2, 'Serenity'),
(3, 'Death Start');
INSERT INTO launch (spacecraft_id, started, success) VALUES
(1, 'January 8 04:05:06 2999 UTC', true),
(2, 'December 1 01:00:00 3432 UTC', true),
(3, 'February 15 00:00:00 4521 UTC', false),
(3, 'July 10 12:05:00 4525 UTC', true);
http://sqlfiddle.com/#!15/a1921
How to select last launch result (launch.success) for each spacecraft?
UPDATE #1
That's my current solution:
SELECT DISTINCT S.*, last_launch, L2.success FROM spacecraft AS S
LEFT OUTER JOIN (SELECT *, MAX(started) OVER (PARTITION BY spacecraft_id) AS last_launch FROM launch) AS L1
ON L1.spacecraft_id=S.id
LEFT OUTER JOIN launch AS L2
ON L2.started=L1.last_launch;