I’m trying to join two tables in a very peculiar way and I can’t find the right query to achieve this.
I want to keep ALL dt1 rows intact and join the first row for each FUND_ID with the respective match from dt2.
See below an example for better understanding
First table: dt1
FUND_ID | Name |
---|---|
1 | Fund1 |
1 | Fund2 |
1 | Fund8 |
2 | Fund3 |
2 | Fund4 |
Second table: dt2
FUND_ID | Value |
---|---|
1 | 100 |
2 | 200 |
Desired Join Result:
FUND_ID | Name | Value |
---|---|---|
1 | Fund1 | 100 |
1 | Fund2 | |
1 | Fund8 | |
2 | Fund3 | 200 |
2 | Fund4 |
I tried multiple SQL Queries, using LEFT JOIN and DISTINCT, but I was not able to achieve the expected result.
I expect an output table with all the rows from dt1 where the first row for each FUND_ID is joined with the respective match from dt2.
2
Answers
This should work
You can assign a row number to each record within each
FUND_ID
in your first table usingROW_NUMBER()
. Then you can join this with the second table, but only include the value from the second table for the first row of eachFUND_ID
.In a few words, rank each row within each
FUND_ID
in the first table, then join it with the second table, but only bring in the value for the first row in each group.