在源和目标相同的表中查找不同的记录

时间:2017-08-10 04:54:12

标签: sql sql-server tsql

我有一个包含列源的表,目的地只想查找源和目标相同的表中的不同记录

Create table test (id int, sources varchar(50), destination varchar(50))


Insert into test(id, sources,destination)
select 1,'delhi', 'mumbai'
union all
select 2,'mumbai','delhi'
union all
select 3, 'delhi', 'nagpur'
union all
select 4, 'lucknow', 'bhopal'
union all
select 5, 'bhopal','lucknow'

4 个答案:

答案 0 :(得分:1)

从测试中选择* 左连接测试p on t.sources = p.destination和t.destination = p.sources 其中t.sources> p.sources或p.sources为null

答案 1 :(得分:0)

select a.id, a.source, a.destination from test a, test b
   where a.destination = b.destination and
         a.source = b.source and
         a.id <> b.id

答案 2 :(得分:0)

尝试这样的事情:

SELECT
  sources,
  destination
FROM test a
WHERE EXISTS (SELECT
  *
FROM test a1
WHERE a1.destination = a.sources
AND a1.sources = a.destination
AND a1.sources > a.sources)
AND (sources != destination)
UNION
SELECT
  sources,
  destination
FROM test a
WHERE sources = destination
AND ((SELECT
  COUNT(*)
FROM test
WHERE sources = a.sources
AND destination = a.sources)
> 1)
ORDER BY sources;

答案 3 :(得分:0)

是吗?

Select distinct source, destination 
into #temp
from test

delete a
from  #temp a, #temp b
where a.source = b.destination
and b.source = a.destination

Select a.id, a.source,b.destination
from test a,#temp b
where a.source = b.source
and a.destination =b.destination

drop table #temp