Sql 在源和目标相同的表中查找不同的记录
我有一个表,其中的source列和destination列是相同的,我只想从表中查找不同的记录,而source和destination列是相同的Sql 在源和目标相同的表中查找不同的记录,sql,sql-server,tsql,Sql,Sql Server,Tsql,我有一个表,其中的source列和destination列是相同的,我只想从表中查找不同的记录,而source和destination列是相同的 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','delh
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'
从测试a、测试b中选择a.id、a.source、a.destination
其中a.destination=b.destination和
a、 source=b.源和
a、 身份证
从测试a、测试b中选择a.id、a.source、a.destination
其中a.destination=b.destination和
a、 source=b.源和
a、 身份证
尝试以下方法:
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;
试着这样做:
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;
是吗
是吗
从测试t中选择*t.sources=p.destination和t.destination=p.sources上的左连接测试p 其中t.sources>p.sources或p.sources为空从测试t中选择* t.sources=p.destination和t.destination=p.sources上的左连接测试p
当t.sources>p.sources或p.sources为空时你能添加你想要的输出吗?嗨,Uttam,谢谢你的回复。我想输出像EID源目的地1德里孟买3德里那格浦尔4博帕尔勒克瑙我想1和2是一样的,4和5也是一样的,对吗?你能添加你想要的输出吗?嗨,Uttam,谢谢你的回复。我想把来源放在目的地1德里孟买3德里那格浦尔4博帕尔卢克瑙我想1和2是一样的,4和5也是一样的,对吧?虽然这可能回答了这个问题,还请添加一个简短的解释,说明您的代码做了什么以及为什么它解决了初始问题。虽然这可能会回答问题,但也请添加一个简短的解释,说明您的代码做了什么以及为什么它解决了初始问题。您能让我知道where子句(t.sources>p.sources)的用法吗你能告诉我where子句(t.sources>p.sources)在这里是如何工作的吗。
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