假设我有一个这样的表:

name | score_a | score_b
-----+---------+--------
 Joe |   100   |   24
 Sam |    96   |  438
 Bob |    76   |  101
 ... |   ...   |  ...

我想选择score_a和score_b的最小值。换句话说,就像:

SELECT name, MIN(score_a, score_b)
FROM table

当然,结果将是:

name | min
-----+-----
 Joe |  24
 Sam |  96
 Bob |  76
 ... | ...

然而,当我在Postgres中尝试这个时,我得到,“没有函数匹配给定的名称和参数类型。您可能需要添加显式类型强制转换。”MAX()和MIN()似乎跨行而不是跨列工作。

有可能做到我正在尝试的事情吗?


当前回答

至少(a, b):

The GREATEST and LEAST 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.5 for details). NULL values in the list are ignored. The result will be NULL only if all the expressions evaluate to NULL. Note that GREATEST and LEAST 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...

其他回答

至少(a, b):

The GREATEST and LEAST 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.5 for details). NULL values in the list are ignored. The result will be NULL only if all the expressions evaluate to NULL. Note that GREATEST and LEAST 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...

下面是PostgreSQL中LEAST()函数的文档链接:

http://www.postgresql.org/docs/current/static/functions-conditional.html#AEN15582

你可以通过将数据放入这样的一列来得到答案:

SELECT name, MIN(score_a, score_b) as minimum_score
FROM table

在这里,我们将score_a和score_b中的最小值放在一起,并通过将该值存储在名为minimum_score的列中打印出来。