Skip to content
Advertisement

bigquery left join by closest previous value

I have two table as below:

TABLE_1:

TABLE_2:

I want to add a column to table_1 to show covered value from table_2. Although timestamps are not matching, I want to get the closest previous timestamp captured in table_2. For example AA was covered at 1:04 and uncovered at 1:06 so result table look like this:

Would you please help me to finish this query:

Advertisement

Answer

BigQuery is not thrilled with non-equijoins. So an alternative is to use union all and some trickery:

This is combining the two tables. The last_value() is then retrieving the most recent covered value — which for table_1 rows will come from table_2.

The final where just filters the result set to only have table_1 rows.

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