Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL query to select one of each kind

Tags:

sql

Let's say I have this table:

id colorName
1 red
2 blue
3 red
4 blue

How can I select one representative of each color?
Result:
1 red
2 blue

like image 676
Bogdan Kanivets Avatar asked Feb 20 '09 22:02

Bogdan Kanivets


People also ask

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.

How do I select a single record in SQL Server?

While the table name is selected type CTRL + 3 and you will notice that the query will run and will return a single row as a resultset. Now developer just has to select the table name and click on CTRL + 3 or your preferred shortcut key and you will be able to see a single row from your table.


1 Answers

Not random representatives, but...

select color, min(id) from   mytable group by color; 
like image 83
Tony Andrews Avatar answered Sep 25 '22 12:09

Tony Andrews