简体   繁体   English

SQL查询 如何仅获取具有两个匹配字段的记录

[英]SQL Query; How to get only records with two matching fields

I hope I can explain this properly, it is a little confusing. 我希望我能正确解释这一点,这有点令人困惑。 I need to query for records that have the same "origin" and the same "destination". 我需要查询具有相同“来源”和相同“目的地”的记录。 My rows will each have an origin and a destination. 我的行将分别具有起点和终点。 I need to see all those in which both match. 我需要查看所有两者都匹配的东西。 So for instance, if there is a row with Seattle (origin) and Portland (destination) I need to see all other records with Seattle as the origin and Portland as the destination. 因此,例如,如果在西雅图(原点)和波特兰(目的地)之间有一行,我需要查看所有其他记录,其中西雅图为出发地,波特兰为目的地。 Additionally, I need to see all records with this type of a match. 另外,我需要查看具有这种匹配类型的所有记录。 So if there are records with the same origin and the same destination (not just seattle and Portland), they would also be displayed. 因此,如果存在具有相同来源和相同目的地的记录(不仅是西雅图和波特兰),那么还将显示它们。 Make sense? 说得通? can you help? 你能帮我吗?

If I understand well, you wanna find duplicates on some fields. 如果我理解得很好,您想在某些字段中找到重复项。

You can do 你可以做

select * 
from YourTable t
join (select origin, destination
      from YourTable
      group by origin, destination
      having count(*) > 1) m
on t.origin = m.origin and t.destination = m.destination

If you don't need all the fields, you could do 如果您不需要所有字段,则可以

select origin, destination, count(*)
from YourTable
group by origin, destination
having count(*) > 1

I wonder if you just want to sort the data: 我想知道您是否只想对数据进行排序:

select t.*
from table t
order by by origin, destination;

This will put rows with common values next to each other. 这将使具有共同值的行彼此相邻。

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

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