How to select distinct record

distinctselect

I have a table, as follows:

ID   |  Name     |  MyID
1    |  Alan     |  2
2    |  Alan     |  2
3    |  John     |  3

I want to select the records as follows:

  1. If two records have the duplicate values in ‘Name’ column, then only the first record is selected and the other record is discarded, even if the two records have different values in other columns.
  2. If two records have different ‘Name’ value, then they are ordered via ‘MyID’ column in ascendant order.
  3. All columns of the records should be returned.

So for the above records, the query should select the following ones:

ID   |  Name     |  MyID
1    |  Alan     |  2
3    |  John     |  3

How to write the query? It seems I should use DISTINCT or GROUP BY, but my queries are all fail. Please help.

Thanks

Best Answer

This query with a DISTINCT:

SELECT DISTINCT Name, MyID
FROM data;

Returns distinct Name and MyID:

Name     |  MyID
Alan     |  2
John     |  3

This query with a GROUP BY:

SELECT MIN(ID) AS ID, Name, MyID
FROM data
GROUP BY Name, MyID;

Returns Name and MyId with the smallest ID like your sample:

ID   |  Name     |  MyID
1    |  Alan     |  2
3    |  John     |  3

Both query are in this SQL Fiddle and will work with most RDBMS. (Sample uses SQL Server)