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

蹲街弑〆低调 提交于 2019-12-11 04:01:25

问题


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%')

回答1:


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)



回答2:


Using MS SQL Server. Check this working code on SQL Fiddle

SELECT T1.Name, T1.Vlan
  FROM yourTable T1
 WHERE NOT EXISTS (SELECT 1 
                     FROM yourTable T2
                    WHERE T2.Vlan = T1.Vlan
                      AND T2.Name <> T1.Name)



回答3:


This should work.

select 
  t1.Name
  ,t1.Vlan
from table t1
left join table t2 
  on t1.Vlan = t2.Vlan 
 and t1.Name='Switch 1' 
 and t2.Name = 'Switch 2'
where  t2.Name is null
union
select 
  t1.Name
  ,t1.Vlan
from table t1
left join table t2 
  on t1.Vlan = t2.Vlan 
 and t1.Name='Switch 2' 
 and t2.Name = 'Switch 1'
where  t2.Name is null



回答4:


SELECT * 
FROM yourTable 
WHERE [Name] = 'Switch1'
AND [Vlan] NOT IN(SELECT [Vlan] FROM yourTable WHERE [Name] = 'Switch2')


Name    Vlan
Switch1 3


来源:https://stackoverflow.com/questions/12472057/how-to-compare-records-within-the-same-table-and-find-missing-records

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!