Search code examples
sqlsql-serverunique

How to compare records within the same table and find missing records


Here is a simplified version of my table

Name      Vlan
Switch 1    1
Switch 1    2
Switch 1    3
Switch 2    1
Switch 2    2

I want to compare all vlans belonging to switch 1 with all vlans belonging to switch 2 and print out the missing ones in one of the switches using SQL query. Is it possible to do so? Note all data resides inside the same table.

On the example data provided above, the query should return Row 3

Switch 1,  3

Here is the query I tried earlier (my requirement has few more conditions than the simplified version in my query):

Select Vlans.VLANID From VLANS
 JOIN Nodes ON 
VLANS.NodeId = Nodes.NodeID
Where Nodes.sysName LIKE 'SSW010%' and Vlans.VlanID NOT In
(Select Vlans.VLANID AS Vlan2 From VLANS
 JOIN Nodes ON 
VLANS.NodeId = Nodes.NodeID
Where Nodes.sysName LIKE 'SSW001%')

Solution

  • This will give you what you're after. It doesn't make any assumptions about the data and will give all missing records. If you want to limit it to just 'Switch 1' then add this to the WHERE clause.

    SELECT
      t1.Name,
      t1.Vlan
    FROM t t1
    WHERE NOT EXISTS (SELECT 1 
                        FROM t t2
                       WHERE t2.Name <> t1.Name
                         AND t2.Vlan = t1.Vlan)
    
    CREATE TABLE t 
    (
      Name VARCHAR(10),
      Vlan INT
    )
    
    
    INSERT INTO t VALUES('Switch 1',1)   
    INSERT INTO t VALUES('Switch 1', 2)
    INSERT INTO t VALUES('Switch 1', 3)
    INSERT INTO t VALUES('Switch 2', 1)
    INSERT INTO t VALUES('Switch 2', 2)