Question

I have database table that looks like:

Email,   IP,   Country
a@a.com 1.2.3.4  Canada
a@b.com 1.4.5.6  France
a@a.com 5.4.3.3  United States
a@c.com 5.4.4.2  Mexico
a@b.com 5.1.1.1  France

The Result that i want:
a@a.com 1.2.3.4  Canada
a@b.com 1.4.5.6  France
a@c.com 5.4.4.2  Mexico

Email is the filtering column. The result should shows only the first 1 it finds by email and remove the others no matter what information they contains.

I tried with Group By and it's impossible since the columns information is different and i need all the information.

Any idea how this can be accomplish with ms sql query?

I am using ms sql 2008

Was it helpful?

Solution

You can use a cte + Row_Number to take only the first (complete) row of each group:

WITH CTE AS
(
    SELECT Email,   IP,   Country
         , RN = ROW_NUMBER() OVER (PARTITION BY Email ORDER BY Email)
    FROM dbo.Emails
)
SELECT Email,   IP,   Country
FROM CTE
WHERE RN = 1

Change the ORDER BY if you want a specific row.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top