繁体   English   中英

我如何找到在两个列值之间切换的行?

[英]How do I find rows where two column values are switched?

我有一个包含三列的表:StartingId,EndingId和TripCount。 起始ID和结束ID分别是旅程开始和结束的位置的PK。 TripCount包含一个整数,代表人们在起始位置和终止位置之间旅行的次数。

有时,一次旅行的结束ID会变成另一次旅行的起始ID。 反转起始和结束ID时,计数也可能会有所不同。

以下是一些示例数据:

StartingId   EndingId   TripCount
100          200        1023
101          300        5214
200          100        600
650          200        100

如何仅返回作为另一次旅程的反向旅程和TripCount的行。 我想要的结果:

StartingId   EndingId   TripCount
100          200        1023
200          100        600

您使用其他别名重新连接到表本身。 您希望一个表的StartingId等于该表的EndingId,反之亦然。

Select 
      t.StartingId, 
      t.EndingId, 
      t.TripCount 
FROM 
      MyTable t 
INNER JOIN 
      MyTable t2 
ON
      t2.StartingId = t.EndingId AND t2.EndingId = t.StartingId

SQL小提琴演示

您可以使用一个exist子句:

select startingID
     , endingID
     , tripCount
  from myTable t
 where exists (select 1
                 from myTable t2
                where t2.startingID = t.endingID 
                  and t2.endingID = t.startingID)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM