SQL SQL查询以选择每种类型之一

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/571478/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 01:11:56  来源:igfitidea点击:

SQL query to select one of each kind

sql

提问by Bogdan Kanivets

Let's say I have this table:

假设我有这张桌子:

id colorName
1 red
2 blue
3 red
4 blue

id 颜色名称
1 红色
2 蓝色
3 红色
4 蓝色

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

如何为每种颜色选择一个代表?
结果:
1红
2蓝

回答by Tony Andrews

Not random representatives, but...

不是随机代表,而是……

select color, min(id)
from   mytable
group by color;

回答by user4812

select distinct colorname from mytable

回答by Quassnoi

In MS SQL Serverand Oracle:

MS SQL ServerOracle

SELECT  id, colorName
FROM    (
        SELECT  id, colorName,
                ROW_NUMBER() OVER (PARTITION BY colorName ORDER BY id) AS rn
        FROM    colors
        ) q
WHERE   rn = 1

回答by Sony G

Here is the easiest way:

这是最简单的方法:

SELECT DISTINCT colorName FROM mytable ORDER BY colorName

回答by dkretz

Try this:

尝试这个:

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

回答by SierraJuliet

SELECT DISTINCT colorname FROM yourtable ORDER BY id; (change id to colorname if desired)

SELECT DISTINCT colorname FROM yourtable ORDER BY id; (如果需要,将 id 更改为 colorname)

or

或者

SELECT colorname FROM yourtable GROUP BY colorname;

SELECT colorname FROM yourtable GROUP BY colorname;