Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

SQL Server – Find NON-duplicate column value combinations

I am new to SQL. This is for a migration script.

CompanyTable:

EmployeeId DivisionId
abc div1
def div1
abc div1
abc div2
xyz div2

In the below code I am Selecting duplicate EmployeeId-DivisionId combinations, that is, the records that have the same EmployeeId and DivisionId will be selected. So from the above table, the two rows that have abc-div1 combination will be selected by the below code.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

How can I invert it? It seems so simple but I can’t figure it out. I tried replacing with HAVING count(*) = 0 instead of > 1, I’ve tried fiddling with the equality signs in the ON and AND lines. Basically from the above table, I want to select the other three rows that don’t have the abc-div1 combination. If there is a way to select all the unique EmployeeID-DivisionId combinations, let me know.

SELECT a.EmployeeID, a.DivisionId FROM CompanyTable a
  JOIN ( SELECT EmployeeID, DivisionId 
         FROM CompanyTable 
         GROUP BY EmployeeID, DivisionId 
         HAVING count(*) > 1 ) b
    ON a.EmployeeID = b.EmployeeID
   AND a.DivisionId = b.DivisionId;

EmployeeId and DivisionId are both nvarchar(50) columns.

>Solution :

As already mentioned, you must replace > 1 by its real opposite <= 1, this works: db<>fiddle

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading