I'm trying to join two tables using a left-join. And the result set has to include only the first record from the "right" joined table.
Lets say I have two tables A and B as below;
Table "A"
code | emp_no 101 | 12222 102 | 23333 103 | 34444 104 | 45555 105 | 56666
Table "B"
code | city | county 101 | Glen Oaks | Queens 101 | Astoria | Queens 101 | Flushing | Queens 102 | Ridgewood | Brooklyn 103 | Bayside | New York
Expected Output:
code | emp_no | city | county 101 | 12222 | Glen Oaks | Queens 102 | 23333 | Ridgewood | Brooklyn 103 | 34444 | Bayside | New York 104 | 45555 | NULL | NULL 105 | 56666 | NULL | NULL
If you notice my result has only the one matched record from table "B"(doesn't matter what record is matched) after left join (and it is a one to many mapping)
I need to pick the first matched record from table B and ignore all other rows.
Please help!
Thanks
SQL LEFT JOIN examples Each location belongs to one and only one country while each country can have zero or more locations. The relationship between the countries and locations tables is one-to-many.
Syntax For Left Join:SELECT column names FROM table1 LEFT JOIN table2 ON table1. matching_column = table2. matching_column; Note: For example, if you have a left table with 10 rows, you are guaranteed to have at least 10 rows after applying join operation on two tables.
To do that, you can use the ROW_NUMBER() function. In OVER() , you specify the groups into which the rows should be divided ( PARTITION BY ) and the order in which the numbers should be assigned to the rows ( ORDER BY ). You assign the row numbers within each group (i.e., year).
The SQL LEFT JOIN returns all rows from the left table, even if there are no matches in the right table. This means that if the ON clause matches 0 (zero) records in the right table; the join will still return a row in the result, but with NULL in each column from the right table.
After playing around a bit, this turns out to be trickier than I'd expected! Assuming that table_b
has some single column that is unique (say, a single-field primary key), it looks like you can do this:
SELECT table_a.code, table_a.emp_no, table_b.city, table_b.county FROM table_a LEFT JOIN table_b ON table_b.code = table_a.code AND table_b.field_that_is_unique = ( SELECT TOP 1 field_that_is_unique FROM table_b WHERE table_b.code = table_a.code ) ;
The highest voted answer does not seem correct to me, and seems overcomplicated. Just group by the code field on table B in your subquery and select the maximum Id per grouping.
SELECT table_a.code, table_a.emp_no, table_b.city, table_b.county FROM table_a LEFT JOIN table_b ON table_b.code = table_a.code AND table_b.field_that_is_unique IN (SELECT MAX(field_that_is_unique) FROM table_b GROUP BY table_b.code)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With