SQL 我如何在postgres sql的列中找到最大值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4910790/
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 09:13:00  来源:igfitidea点击:

How do i find the largest value in a column in postgres sql?

sqlpostgresqlmax

提问by raveren

For example:

例如:

name | weight
jon    100    
jane   120    
joe    130

How do I only return the name of the person with the largest weight?

如何只返回权重最大的人的名字?

采纳答案by Hao

Use this:

用这个:

select name
from tbl
where weight = (select max(weight) from tbl)

回答by raveren

SELECT name FROM tbl ORDER BY weight DESC LIMIT 1

Much more performant than the other answer and results in one row only.

比另一个答案的性能要高得多,并且只产生一行。

回答by Matt Kleinsmith

ORDER BY DESC puts rows with null values at the top.

ORDER BY DESC 将具有空值的行放在顶部。

To avoid returning results corresponding to null values:

为避免返回对应于空值的结果:

SELECT name FROM tbl WHERE weight = (SELECT MAX(weight) FROM tbl);

SELECT name FROM tbl WHERE weight = (SELECT MAX(weight) FROM tbl);

Note: This query will return multiple results if multiple people have a weight equal to the maximum weight. To grab just one, add LIMIT 1to the end of the query.

注意:如果多人的权重等于最大权重,则此查询将返回多个结果。要仅获取一个,请添加LIMIT 1到查询的末尾。



Acknowledgements and more information:

致谢和更多信息:

Why do NULL values come first when ordering DESC in a PostgreSQL query?

为什么在 PostgreSQL 查询中对 DESC 进行排序时首先出现 NULL 值?

MIN/MAX vs ORDER BY and LIMIT

MIN/MAX 与 ORDER BY 和 LIMIT

Postgres MAX Function

Postgres MAX 函数

回答by alexkovelsky

If you need to find multiple rows, e.g. date on which each person had maximum weight:

如果您需要查找多行,例如每个人体重最大的日期:

name | weight | day
don    110      1
don    120      20
don    110      30
joe    90       1
joe    80       15
joe    85       30

i.e. for "don" you want to get "don | 120 | 20"and for joe you want "joe | 90 | 1", then you can write:

即对于你想要的“don”和你想要"don | 120 | 20"的 joe "joe | 90 | 1",那么你可以写:

SELECT name, max(weight), (array_agg(day ORDER BY weight DESC))[1] FROM tbl GROUP BY name