2013-02-26 77 views
10

我確定這很簡單,但是我嘗試過的每個示例都失敗了。我想查詢一個表像這樣從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但只需在一張桌上完成。該查詢將爲每一行找到一個匹配項,但我只希望在兩列中具有匹配值的行。我如何去尋找?

謝謝

+0

什麼都要公頃如果三行都有相同的Part_Type和Station_Type? – hatchet 2013-02-26 23:52:12

+0

它應該返回所有三個。基本上我正在尋找返回每個具有匹配列的行的「組」。 – user912447 2013-02-27 13:07:10

回答

14

您可以使用以下方法:

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

根據要求,我建議用'count count(id)> 1'來代替'having count(id)= 2'。沿着這些線:http://www.sqlfiddle.com/#!3/48af7/ 6 – 2013-02-26 23:42:26

+1

@zespri你可能是對的,更新。謝謝:) – Taryn 2013-02-26 23:45:07

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 
+2

你需要一些東西來避免重複。正如所寫的每一行將永遠匹配自己。 – hatchet 2013-02-26 23:32:22

+0

糟糕,你說的沒錯。更新了我的答案,並向上提出了你的答案。 – 2013-02-26 23:47:55

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) 
+0

bluefeet的答案都是有效的,我接受他的唯一原因就是他輸入的「group by」。它使得信息更容易閱讀。 – user912447 2013-02-27 13:12:53

相關問題