Skip to content
Advertisement

Find closest match to value in another table

I have a table_a with many rows and columns for each timestamp in PostgreSQL 13. I’m trying to find the row where the value in column X is closest to a benchmark value obtained from another table. This second table has only a single benchmark value for each timestamp. For each timestamp, I need to return most of the columns of table_a. The query below works fine when supplying the value for the benchmark directly.

How can I get the benchmark value from table_b to use in this query?

Simply substituting table_b.benchmark with (SELECT benchmark FROM table_b WHERE table_a.timestamp = table_b.timestamp) results in ‘relation “t1” does not exist’ error.

Could not figure out a working join either.

table_a:

table_b:

Expected result:

SQL query:

Advertisement

Answer

One option uses a lateral join:

You can also use distinct on:

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement