I have two tables in postgres.
CREATE TABLE data (
name VARCHAR(10) PRIMARY KEY
);
CREATE TABLE timeseries (
name VARCHAR(10) NOT NULL REFERENCES data(name),
time TIMESTAMP NOT NULL,
value INTEGER NOT NULL,
PRIMARY KEY (name, time)
);
How I can join timeseries table to data table in such way I’ll get value
column with latest timestamp
2
Answers
You can extract the latest records of
timeseries
table pername
into a CTE usingdistinct on
with custom order by and then join withdata
table (supposing that it has more columns and the above is just an illustration).The basic technique for this kind of tasks – use CTE with ROW_NUMBER window function:
Within CTE we get all rows numbered according their timestamp in DESC order, so last row get row number = 1, after that we filter result of CTE for rows with number 1
Test the solution here