As-Of Join Latest Price Per Event
Attach the most recent price at or before each trade with a timestamp-filtered LEFT JOIN plus DISTINCT ON, and the ROW_NUMBER window form as an alternative.
Code
CREATE TABLE trades (
event_id int PRIMARY KEY,
asset text NOT NULL,
traded_at timestamptz NOT NULL
);
CREATE TABLE prices (
asset text NOT NULL,
priced_at timestamptz NOT NULL,
price numeric NOT NULL
);
INSERT INTO trades VALUES
(1, 'AAPL', '2026-01-05 10:00+00'),
(2, 'AAPL', '2026-01-05 16:30+00');
INSERT INTO prices VALUES
('AAPL', '2026-01-04 20:00+00', 180),
('AAPL', '2026-01-05 11:00+00', 182),
('AAPL', '2026-01-06 20:00+00', 190);
-- As-of join:每个成交只配 priced_at <= traded_at 的最新一行
-- LEFT JOIN 先按时间放行全部候选,DISTINCT ON 按事件取最新一条
SELECT DISTINCT ON (t.event_id)
t.event_id, t.traded_at, p.priced_at, p.price
FROM trades t
LEFT JOIN prices p
ON p.asset = t.asset
AND p.priced_at <= t.traded_at
ORDER BY t.event_id, p.priced_at DESC;
-- 等价窗口写法:先按事件编号再筛 1 号
WITH matched AS (
SELECT t.event_id, t.traded_at, p.priced_at, p.price,
ROW_NUMBER() OVER (PARTITION BY t.event_id ORDER BY p.priced_at DESC) AS rn
FROM trades t
LEFT JOIN prices p
ON p.asset = t.asset
AND p.priced_at <= t.traded_at
)
SELECT event_id, traded_at, priced_at, price
FROM matched
WHERE rn = 1
ORDER BY event_id;Inside the snippet
What runs here is SELECT / INSERT / CREATE — trades, prices and matched are the objects involved.
Concretely, the SQL combines: a CTE (WITH … AS) that names an intermediate result before the main query; 2 JOINs combining rows across tables; a WHERE clause limiting a statement to the rows that qualify; a window function (OVER (…)) deriving per-row results from surrounding rows without collapsing the set; an ORDER BY that fixes the output order; a DISTINCT qualifier that collapses duplicate rows; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity.
What to watch for
- Row counts compound across 2 joins; make sure the join keys are indexed before adapting this to production data volumes.
- Window functions are evaluated after
WHEREandGROUP BY— their output is not visible to a same-levelWHERE.
Putting it to use
The trades table is the working surface here.
Core lines
SELECT DISTINCT ON (t.event_id)
t.event_id, t.traded_at, p.priced_at, p.price
FROM trades t
LEFT JOIN prices p
ON p.asset = t.asset
AND p.priced_at <= t.traded_at
ORDER BY t.event_id, p.priced_at DESC;
INSERT INTO prices VALUES
('AAPL', '2026-01-04 20:00+00', 180),
('AAPL', '2026-01-05 11:00+00', 182),
('AAPL', '2026-01-06 20:00+00', 190);
CREATE TABLE prices (
asset text NOT NULL,
priced_at timestamptz NOT NULL,
price numeric NOT NULL
);
Interactive Tools for This Topic
FAQ
- Which objects does the SQL touch?
- `trades`, `prices`, `matched` — joined via 2 JOIN clauses.
Report a problem with this exampleOpens a pre-filled issue on GitHub.