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

时间:2013-02-26 23:24:43

标签: 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

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

谢谢

3 个答案:

答案 0 :(得分:16)

您可以使用以下内容:

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)

请参阅SQL Fiddle with Demo

答案 1 :(得分:3)

select id, part_type, station_type 
from myTable t1
where exists (select 1 from myTable t2
              where t1.part_type = t2.part_type
                  and t1.station_type = t2.station_type
                  and t1.id <> t2.id)

答案 2 :(得分:1)

我认为self-join会对你有用:

SELECT * FROM table t1 
INNER JOIN table t2 ON t1.Part_Type = t2.Part_Type 
  AND t1.Station_Type = t2.Station_Type
  AND t1.Id <> t2.Id