Search code examples
sqlduplicateswhere-clauseprocedureclause

SQL - Removing Duplicate without 'hard' coding?


Heres my scenario.

I have a table with 3 rows I want to return within a stored procedure, rows are email, name and id. id must = 3 or 4 and email must only be per user as some have multiple entries.

I have a Select statement as follows

SELECT
     DISTINCT email,
     name,
     id
from table
where
     id = 3
     or id = 4

Ok fairly simple but there are some users whose have entries that are both 3 and 4 so they appear twice, if they appear twice I want only those with ids of 4 remaining. I'll give another example below as its hard to explain.

Table -

Email              Name    Id
jimmy@domain.com   jimmy   4
brian@domain.com   brian   4
kevin@domain.com   kevin   3
jimmy@domain.com   jimmy   3

So in the above scenario I would want to ignore the jimmy with the id of 3, any way of doing this without hard coding?

Thanks


Solution

  • SELECT
         email,
         name,
         max(id)
    from table
    where
         id in( 3, 4 )
    group by email, name