how to select rows based on distinct values of A COLUMN only how to select rows based on distinct values of A COLUMN only sql-server sql-server

how to select rows based on distinct values of A COLUMN only


Looking at your output maybe the following query can work, give it a try:

SELECT * FROM tablenameWHERE id IN(SELECT MIN(id) FROM tablename GROUP BY EmailAddress)

This will select only one row for each distinct email address, the row with the minimum id which is what your result seems to portray


Try this - you need a CTE (Common Table Expression) that partitions (groups) your data by distinct e-mail address, and sorts each group by ID - smallest first. Then you just select the first entry for each group - that should give you what you're looking for:

;WITH DistinctMails AS(    SELECT ID, MailID, EMailAddress, NAME,        ROW_NUMBER() OVER(PARTITION BY EMailAddress ORDER BY ID) AS 'RowNum'    FROM dbo.YourMailTable)SELECT *FROM DistinctMailsWHERE RowNum = 1

This works on SQL Server 2005 and newer (you didn't mention what version you're using...)


use this(assume that your table name is emails):

select * from emails as a inner join  (select EmailAddress, min(Id) as id from emails group by EmailAddress ) as b on a.EmailAddress = b.EmailAddress and a.Id = b.id

hope this help..