假设我有这张表:
id colorName
1 red
2 blue
3 red
4 blue
如何选择每种颜色的一个代表?
结果:
1红
2蓝
不是随机代表,而是......
select color, min(id) from mytable group by color;
select distinct colorname from mytable
在MS SQL Server
和Oracle
:
SELECT id, colorName FROM ( SELECT id, colorName, ROW_NUMBER() OVER (PARTITION BY colorName ORDER BY id) AS rn FROM colors ) q WHERE rn = 1