Sql-server – Identify changes across records for the field ID

rowsql server

Consider the following table

TabName     ID      Gender    FirstName 
Tab1        C1      M         John   
Tab2        C1      M         John   
Tab3        C1      F         John   
Tab1        C2      F         Mary  
Tab2        C2      F         Mary  
Tab3        C2      F         Mary  

I am looking to identify individual IDs where there is inconsistency across the 'tabs'. For example, ID 'C1' is not the same in tabs 'Tab1' and 'Tab2', however, has a change in the Gender field in 'Tab3'. On the other hand, 'Mary' is consistent across all three tabs.

A potential approach may be to find 'ID' where the count of duplicates records (each row is exactly the same) is not equal to the count of occurrences of each 'ID'.

However, I am not sure how I would write the above SQL. Additionally, I think there is probably a better and cleaner approach to this problem.

Best Answer

SELECT id
FROM table
GROUP BY id
HAVING COUNT(DISTINCT gender) != 1
    OR COUNT(DISTINCT FirstName) != 1