【问题标题】:Select Rows with matching columns from SQL Server从 SQL Server 中选择具有匹配列的行
【发布时间】:2013-02-27 07:49:04
【问题描述】:

我相当肯定这很简单,但是我尝试过的每个示例都失败了。我想查询这样的表

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,但只需要在一张桌子上完成。该查询将为每一行找到匹配项,但我只想要在两列中具有匹配值的行。我该如何找到它?

谢谢

【问题讨论】:

  • 如果三行都具有相同的 Part_Type 和 Station_Type 会发生什么?
  • 它应该返回所有三个。基本上我希望返回每个具有匹配列的行的“组”。

标签: sql-server


【解决方案1】:

您可以使用以下内容:

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

【讨论】:

  • 根据要求,我建议将 having count(id) = 2 替换为 having count(id) > 1 类似的东西:sqlfiddle.com/#!3/48af7/6
【解决方案2】:
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)

【讨论】:

  • 你的一个蓝脚的答案都有效,我接受他的唯一原因是他输入的“分组依据”。它使信息更容易阅读。
  • 这个答案比接受的答案更简短,对我来说更容易理解。
【解决方案3】:

我认为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

【讨论】:

  • 你需要一些东西来避免重复。正如所写的那样,每一行都将始终匹配自身。
  • 哎呀,你是对的,没有考虑清楚。更新了我的答案并为你的答案投票。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-30
  • 1970-01-01
相关资源
最近更新 更多