sql:选择行,其中一些值相等(不是全部)

时间:2016-01-11 15:23:28

标签: sql db2

前置条件:

表,如

id value1 value2 value3
1   x       y      z
2   x       y      x 
3   x       z      y
4   y       x      z
5   x       x      z

任务:make query,它将选择所有行,其中“pairs”(value1和value2)等于行(例如,对于我们的情况,结果应该是第1行和第2行:

  id value1 value2 value3
    1   x       y      z
    2   x       y      x 

我们不知道,表格中可能包含哪些值。

所以,这就是重点。

4 个答案:

答案 0 :(得分:1)

您可以使用窗口功能执行此操作:

select t.*
from (select t.*, count(*) over (partition by value1, value2) as cnt
      from t
     ) t
 where cnt >= 2;

答案 1 :(得分:1)

您可以使用INNER JOIN操作:

SELECT t1.id, t1.value1, t1.value2
FROM mytable AS t1
INNER JOIN mytable AS t2 
ON t1.id <> t2.id AND t1.value1 = t2.value1 AND t1.value2 = t2.value2

答案 2 :(得分:0)

select * from your_table
where id in
(
  select id
  from your_table
  group by value1, value2
  having count(*) > 1
)

答案 3 :(得分:0)

select t1.* from Table t1, Table t2
where t1.value1 =t2.value1
and t1.value2=t2.value2
and t1.id<>t2.id
and t1.value1 <>t1.value2