Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pick distinct rows based on two tables T-SQL

Consider the tables in image

enter image description here

How to select rows from Table1 excluding items from Table2 with same ReferenceId?

The result should be

enter image description here

like image 997
Karthik Avatar asked Mar 15 '26 03:03

Karthik


2 Answers

You can JOIN the tables on ReferenceId, using a LEFT OUTER join and restrict the return values to where the ReferenceId is NULL on Table2.

SELECT * FROM Table1 LEFT JOIN Table2 ON Table1.ReferenceId = Table2.ReferenceId
WHERE Table2.ReferenceId IS NULL
like image 98
Rikalous Avatar answered Mar 17 '26 04:03

Rikalous


You can use something like:

SELECT  Id
        ,ReferenceId
FROM    Table1
WHERE   ReferenceId NOT IN (SELECT DISTINCT ReferenceId FROM Table2);
like image 31
Josien Avatar answered Mar 17 '26 02:03

Josien



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!