1

I'm not sure if the solution for this question is incredible simple or not possible in pure SQL.


I have a simple table with 2 columns

Number    Text
1         a
1         b
2         m
3         x
3         y
3         z

Now the task is: Search all repeated numbers and show the "Text" which uses these duplicated numbers.

We see: 1 is used twice (with a and b), 3 is used with x and y and z. But no line is completely duplicated.

Edit: So I expect something like this.

   Dup_Num    Text
    1         a
    1         b
    3         x
    3         y
    3         z

The search for the duplicate is easy, but I don't have an idea how to connect is with "Text", because when I add "Text" to my SELECT I have to use it for GROUP and this give no duplicates ..

Thanks for help on a lousy day ..

4 Answers4

1

The canonical way to find duplicates in SQL is the self join.

In your example:

select s1.*
from stuff s1
inner join stuff s2
  on s1.number = s2.number
  and s1.text <> s2.text
Neville Kuyt
  • 29,247
  • 1
  • 37
  • 52
1

If I understand correctly, you can use exists:

select t.*
from t
where exists (select 1 from t t2 where t2.number = t.number and t2.text <> t.text)
order by t.number;

For performance, you want an index on (number, text).

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

In your case, you might want to use LISTAGG to group those values and its relation to the other column

SQL> with result 
as (
select '1' as c1 , 'a' as c2 from dual union all
select '1' as c1 , 'b' as c2 from dual union all
select '2' as c1 , 'm' as c2 from dual union all
select '3' as c1 , 'x' as c2 from dual union all
select '3' as c1 , 'y' as c2 from dual union all
select '3' as c1 , 'z' as c2 from dual )
select c1, listagg(c2,',') within group(order by c1) as c3 from result
group by c1;

C C3
- --------------------
1 a,b
2 m
3 x,y,z

SQL>
Roberto Hernandez
  • 8,231
  • 3
  • 14
  • 43
0

This might also help you.

 select * from t where Number in 
 (select Number from t group by Number having count(*) > 1)
 order by Text

Fiddle

Dilhan Nakandala
  • 301
  • 5
  • 24