Question

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

Was it helpful?

Solution

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

OTHER TIPS

Is this what you want to achieve?

SELECT Email, Name, MAX(Id) FROM Table WHERE Id IN (3, 4) GROUP BY Email;

Sometimes using Having Count(*) > 1 may be useful to find duplicated records.

select * from table group by Email having count(*) > 1

or

select * from table group by Email having count(*) > 1 and id > 3.

The solution provided before with the select MAX(ID) from table sounds good for this case. This maybe an alternative solution.

What RDMS are you using? This will return only one "Jimmy", using RANK():

SELECT A.email, A.name,A.id
FROM SO_Table A
INNER JOIN(
SELECT 
email, name,id,RANK() OVER (Partition BY name ORDER BY ID DESC) AS COUNTER
FROM SO_Table B  
) X ON X.ID = A.ID AND X.NAME = A.NAME
WHERE X.COUNTER = 1

Returns:

 email          name    id
 ------------------------------
 jimmy@domain.com   jimmy   4
 brian@domain.com   brian   4
 kevin@domain.com   kevin   3
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top