假设我有这张表:
id colorName
1红色
2蓝色
3红色
4蓝色
如何选择每种颜色的一个代表?
结果:
1红色
2蓝色
答案 0 :(得分:42)
不是随机代表,而是......
select color, min(id)
from mytable
group by color;
答案 1 :(得分:12)
select distinct colorname from mytable
答案 2 :(得分:10)
在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
答案 3 :(得分:4)
试试这个:
SELECT colorName,
MIN(id) AS id
FROM table
GROUP BY colorname
答案 4 :(得分:3)
这是最简单的方法:
SELECT DISTINCT colorName FROM mytable ORDER BY colorName
答案 5 :(得分:0)
SELECT DISTINCT colorname FROM yourtable ORDER BY id; (如果需要,将id更改为colorname)
或
SELECT colorname From yourtable GROUP BY colorname;