选择一列或两列中的数据相同的数据

时间:2018-02-16 14:30:30

标签: mysql r dataframe

我在数据库中有以下提到的数据:

ID      V1   V2
1       A    B
2       A    B
3       A    C
4       X    Y
5       W    V
6       R    V

所需输出:(其中V1或V2或两者中的值相同。)

ID     V1    V2
1       A    B
2       A    B
3       A    C
5       W    V
6       R    V

此外,在获得输出后,MysqlR中有任何方式添加状态列,显示哪个值重复V1(如果V1 }重复),V2(如果V2重复)和Both(如果V1V2都重复。

所需输出:(其中V1或V2或两者中的值相同。)

ID     V1    V2  Identifier
1       A    B   Both
2       A    B   Both
3       A    C   V1
5       W    V   V2
6       R    V   V2

2 个答案:

答案 0 :(得分:2)

我想你想要:

select t.*
from t
where exists (select 1 from t t2 where t2.v1 = t.v1 and t2.id <> t.id) or
      exists (select 1 from t t2 where t2.v2 = t.v2 and t2.id <> t.id) ;

答案 1 :(得分:0)

这应该有效:

select distinct same.id, same.v1, same.v2 from same 
join(
    select V1 as v, count(V1) as c from same group by V1 having count(V1) > 1  
    union
    select V2 as v, count(V2) as c from same group by V2 having count(V2) > 1
) a on a.v = same.V1 or a.v = same.v2