Skip to content
Advertisement

How to join two tables based on FIRST VALUE of a group

Objective: I would like to join two tables based on the first value of Id column grouped by subscription Id column ordered by created_at column.

Situation:

Table1 looks like this:

Table2:

I need to take the earliest Id in table 2 grouped by subscription Id and inner join it with Table 1. So in this example, my output would be

What i tried: I thought about using the FIRST_VALUE but im stuck as to how I can connect them

Fiddle info:

Obviously this doesn’t work due to the ON clause. Does this situation require a row_number function with a cross apply instead? Is there a better way of doing this? Is FIRST_VALUE the wrong function to use ?

Advertisement

Answer

you can use row_number() with order by create_at date which will take 1st id

demo link

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