-1

I have the following table:

name  email              number  type
1     [email protected]     10     A
1     [email protected]     10     B
2     [email protected]         20     B
3     [email protected]         30     B
1     [email protected]     10     A
4     [email protected]         60     A

I want the following:

Result

name  email              number  type
1     [email protected]     10     A
1     [email protected]     10     B
1     [email protected]     10     A

Basically, I want to find the first lines where the three columns (name, email, number) are identical and see them, regardless of type.

How can I achieve this in SQL? I don't want a result with every combination once, I want to see every line that is in the table multiple times.

I thought of doing a group by but a group by gives me only the unique combinations and every line once. I tried it with a join on the table itself but somehow it got too bloated.

Any ideas?

EDIT: I want to display the type column as well, so group by isn't working and therefore, it's not a duplicate.

1
  • 1
    Tag your question with the database you are using. Commented May 17, 2018 at 13:56

3 Answers 3

1

You can use exists for that case :

select t.*
from table t 
where exists (select 1 
              from table 
              where name = t.name and email = t.email and 
                    number = t.number and type <> t.type);

You can also use window function if your DBMS support

select * 
from (select *, count(*) over (partition by name, email, number) Counter 
      from table
     ) t
where counter > 1;
Sign up to request clarification or add additional context in comments.

Comments

1

Core SQL-99 compliant solution.

Have a sub-query that returns name, email, number combinations having duplicates. JOIN with that result:

select t1.*
from tablename t1
join (select name, email, number
      from tablename
      group by name, email, number
      having count(*) > 1) t2
on  t1.name = t2.name
and t1.email = t2.email
and t1.number = t2.number

Comments

1

You can use window functions:

select t.*
from (select t.*, count(*) over (partition by name, email, number) as cnt
      from t
     ) t
where cnt > 1;

If you only want combos that have different types (which might be your real problem), I would suggest exists:

select t.*
from t
where exists (select 1 
              from t t2
              where t2.name = t.name and t2.email = t.email and t2.number = t.number and t2.type <> t.type
             );

For performance, you want an index on (name, email, number, type) for this version.

1 Comment

I tried this one and the query was just going on for too long. My table is 100.000 lines long, so maybe that is why.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.