一个sql查询,用于获取5列相同但只有一列不同的所有记录

时间:2018-05-18 16:59:04

标签: sql sql-server redundancy

我有这张桌子:

A   B   C   D
1  Cat XYZ 12
1  Cat XYZ 13
1  Dog XYZ 14
2  Dog ABC 15
2  Dog ABC 16
3  Cat XYZ 17

结果集:

A   B   C   D
1  Cat XYZ 12
1  Cat XYZ 13
2  Dog ABC 15
2  Dog ABC 16

我需要在我的表中记录所有这些记录,其中A,B,C应该相同,D列可以变化。 请尽快帮助,以寻求帮助。

5 个答案:

答案 0 :(得分:3)

您可以使用exists

select t.* 
from table t
where exists (select 1
              from table t1
              where t1.a = t.a and t1.b = t.b and t1.c = t.c and t1.d <> t.d
              );

答案 1 :(得分:0)

鉴于您希望一列不同,您需要确定要选择的 D列的值。

SELECT A, B, C, MAX(D) D
FROM table
GROUP BY A, B, C

在上述解决方案中,我选择了 D 列的最大值。

答案 2 :(得分:0)

如果您只想要a,b,c值,则可以使用聚合:

select a, b, c, min(d), max(d)
from t
group by a, b, c
having min(d) <> max(d);

如果你想要实际的行,那么Yogesh的exists解决方案可能是最好的方法,假设没有列值是NULL

答案 3 :(得分:0)

这应该这样做。

select * 
from ( select a, b, c, d, 
       count() over (partition by a, b, c) cnt
       from t1
     ) t 
where t.cnt > 1

答案 4 :(得分:-1)

应该可以通过

的简单组来完成此操作
SELECT A, B, C, D
FROM table
GROUP BY A, B, C, D