从SQL Server中选择具有匹配列的行

use*_*447 15 sql-server

我很确定这很简单,但我尝试的每个例子都失败了.我想查询这样的表

ID   Part_Type   Station_Type
---  ---------   ------------
1    5           234
2    5           846
3    5           234
4    6           585
5    6           585
6    7           465
Run Code Online (Sandbox Code Playgroud)

并返回行1和3,以及4和5.也就是说,我想返回两列匹配的行.它类似于这个问题:SO问题但只需要在一张桌子上完成.该查询将为每一行找到匹配项,但我只希望在两列中具有匹配值的行.我怎么去找那个?

谢谢

Tar*_*ryn 17

您可以使用以下内容:

select t1.id, t1.part_type, t1.station_type
from yourtable t1
where exists (select part_type, station_type
              from yourtable t2
              where t1.part_type = t2.part_type
                and t1.station_type = t2.station_type
              group by part_type, station_type
              having count(id) > 1)
Run Code Online (Sandbox Code Playgroud)

请参阅SQL Fiddle with Demo

  • 根据要求,我建议将`having count(id)= 2`替换为`having count(id)> 1`这些内容:http://www.sqlfiddle.com/#!3/48af7/6 (2认同)