Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

select unique rows based on single distinct column

I want to select rows that have a distinct email, see the example table below:

+----+---------+-------------------+-------------+ | id | title   | email             | commentname | +----+---------+-------------------+-------------+ |  3 | test    | [email protected]   | rob         | |  4 | i agree | [email protected]   | rob         | |  5 | its ok  | [email protected]   | rob         | |  6 | hey     | [email protected]   | rob         | |  7 | nice!   | [email protected] | simon       | |  8 | yeah    | [email protected]  | john        | +----+---------+-------------------+-------------+ 

The desired result would be:

+----+-------+-------------------+-------------+ | id | title | email             | commentname | +----+-------+-------------------+-------------+ |  3 | test  | [email protected]   | rob         | |  7 | nice! | [email protected] | simon       | |  8 | yeah  | [email protected]  | john        | +----+-------+-------------------+-------------+ 

Where I don't care which id column value is returned. What would be the required SQL?

like image 734
Adam Avatar asked Nov 25 '11 20:11

Adam


People also ask

How do I get distinct on only one column?

Adding the DISTINCT keyword to a SELECT query causes it to return only unique values for the specified column list so that duplicate rows are removed from the result set.

How do you SELECT only the first rows for each unique value of a column in SQL?

How do you SELECT the first row of each unique value of a column in SQL? You can use row_number() to get the row number of the row. It uses the over command – the partition by clause specifies when to restart the numbering and the order by selects what to order the row number on.


2 Answers

Quick one in TSQL

SELECT a.* FROM emails a INNER JOIN    (SELECT email,     MIN(id) as id   FROM emails    GROUP BY email  ) AS b   ON a.email = b.email    AND a.id = b.id; 
like image 113
Turbot Avatar answered Oct 09 '22 07:10

Turbot


I'm assuming you mean that you don't care which row is used to obtain the title, id, and commentname values (you have "rob" for all of the rows, but I don't know if that is actually something that would be enforced or not in your data model). If so, then you can use windowing functions to return the first row for a given email address:

select     id,     title,     email,     commentname  from ( select      *,      row_number() over (partition by email order by id) as RowNbr   from YourTable ) source  where RowNbr = 1 
like image 44
Adam Robinson Avatar answered Oct 09 '22 08:10

Adam Robinson