SQL 如何获得 Postgres 中两个字段的 MIN()?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/318988/
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
How do I get the MIN() of two fields in Postgres?
提问by mike
Let's say I have a table like this:
假设我有一张这样的表:
name | score_a | score_b
-----+---------+--------
Joe | 100 | 24
Sam | 96 | 438
Bob | 76 | 101
... | ... | ...
I'd like to select the minimum of score_a and score_b. In other words, something like:
我想选择 score_a 和 score_b 的最小值。换句话说,类似于:
SELECT name, MIN(score_a, score_b)
FROM table
The results, of course, would be:
结果当然是:
name | min
-----+-----
Joe | 24
Sam | 96
Bob | 76
... | ...
However, when I try this in Postgres, I get, "No function matches the given name and argument types. You may need to add explicit type casts." MAX() and MIN() appear to work across rowsrather than columns.
但是,当我在 Postgres 中尝试这个时,我得到,“没有函数匹配给定的名称和参数类型。您可能需要添加显式类型转换。” MAX() 和 MIN() 似乎跨行而不是跨列工作。
Is it possible to do what I'm attempting?
有可能做我正在尝试的事情吗?
回答by cagcowboy
LEAST(a, b):
最少(a, b):
The
GREATEST
andLEAST
functions select the largest or smallest value from a list of any number of expressions. The expressions must all be convertible to a common data type, which will be the type of the result (see Section 10.5for details). NULL values in the list are ignored. The result will be NULL only if all the expressions evaluate to NULL.Note that
GREATEST
andLEAST
are not in the SQL standard, but are a common extension. Some other databases make them return NULL if any argument is NULL, rather than only when all are NULL...
该
GREATEST
和LEAST
功能中选择任意数量的表达式的列表,最大或最小值。表达式必须都可以转换为通用数据类型,这将是结果的类型(有关详细信息,请参阅第 10.5 节)。列表中的 NULL 值将被忽略。仅当所有表达式的计算结果都为 NULL 时,结果才会为 NULL。请注意,
GREATEST
和LEAST
不在 SQL 标准中,而是一个常见的扩展名。如果任何参数为 NULL,而不是仅当所有参数为 NULL 时,其他一些数据库使它们返回 NULL...
回答by Bill Karwin
Here's the link to docs for the LEAST()
function in PostgreSQL:
这是LEAST()
PostgreSQL 中函数的文档链接:
http://www.postgresql.org/docs/current/static/functions-conditional.html#AEN15582
http://www.postgresql.org/docs/current/static/functions-conditional.html#AEN15582
回答by Mohamed Aamir
You can get the answer by putting that data into a column like this:
您可以通过将该数据放入这样的列中来获得答案:
SELECT name, MIN(score_a, score_b) as minimum_score
FROM table
Here, we are putting the minimum value among score_a
and score_b
and printing the same by storing that value in a column named minimum_score
.
在这里,我们将最小值放在和之间score_a
,score_b
并通过将该值存储在名为 的列中来打印相同的值minimum_score
。