-3

I have this table:

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

Result set:

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

I need all such records in my table where A, B, C should be same and the D column can vary. Please help it soon that's why asking for help.

Jini
  • 11
  • 3

5 Answers5

3

You can use 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
              );
Yogesh Sharma
  • 49,870
  • 5
  • 26
  • 52
0

Given that you want one column to be different, you would need to decide on what value of Column D you want to be chosen.

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

In the above solution, I went the the maximum value of column D.

Tolu
  • 175
  • 4
  • 10
  • 1
    This wouldn't give the same result as they are expecting – Kevin Mee May 18 '18 at 17:09
  • OP stated that the one column (*D*) is different. So, although the sample data seems to identify same value for column D, grouping all columns would conflict with the question. – Tolu May 18 '18 at 17:11
  • if you group by all the columns then they will result it two separate rows in the result because column D is different – Kevin Mee May 18 '18 at 17:15
  • correct. Looks like we differ on the interpretation of the question. my understanding is that the data set contains rows that are identical when from columns **A**, through **C**, but different for column**D**. – Tolu May 18 '18 at 17:20
  • Very true -- rereading the question right now looks like they dont even have all potential groupings in their results – Kevin Mee May 18 '18 at 17:22
0

If you just want the a, b, c values, you can use aggregation:

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

If you want the actual rows, then Yogesh's solution with exists is probably the best approach, assuming none of the column values are NULL.

Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
0

This should do it.

select * 
from ( select a, b, c, d, 
       count() over (partition by a, b, c) cnt
       from t1
     ) t 
where t.cnt > 1
paparazzo
  • 44,497
  • 23
  • 105
  • 176
-1

Should be able to do this with a simple group by

SELECT A, B, C, D
FROM table
GROUP BY A, B, C, D
Kevin Mee
  • 539
  • 3
  • 14