tags:

views:

636

answers:

4

Let's say I have this table:

id colorName
1 red
2 blue
3 red
4 blue

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

Thanks.

+12  A: 

Not random representatives, but...

select color, min(id)
from   mytable
group by color;
Tony Andrews
+1  A: 

SELECT colorName,
MIN(id) AS id
FROM table
GROUP BY colorname

le dorfier
+3  A: 
select distinct colorname from mytable
he needs the id too.
Seun Osewa
+1  A: 

In MS SQL Server and Oracle:

SELECT id, colorName
FROM (
  SELECT id, colorName,
         ROW_NUMBER() OVER (PARTITION BY colorName ORDER BY id) AS rn
  FROM colors
)
WHERE rn = 1
Quassnoi
Thats a lot of code to do a MIN(id)... ;)
Arjan Einbu
If there is a third field, MIN won't work :)
Quassnoi
You need to put an alias name after the parenthesis to get this to work on MS SQL
Brett G