postgresql 如何在 Postgres/SQL 中获得两个整数的最小值/最大值?

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

How to get min/max of two integers in Postgres/SQL?

postgresql

提问by HRJ

How do I find the maximum (or minimum) of two integers in Postgres/SQL? One of the integers is not a column value.

如何在 Postgres/SQL 中找到两个整数的最大值(或最小值)?整数之一不是列值。

I will give an example scenario:

我将给出一个示例场景:

I would like to subtract an integer from a column (in all rows), but the result should not be less than zero. So, to begin with, I have:

我想从一列(在所有行中)减去一个整数,但结果不应小于零。所以,首先,我有:

UPDATE my_table
SET my_column = my_column - 10;

But this can make some of the values negative. What I would like (in pseudo code) is:

但这会使某些值变为负值。我想要的(伪代码)是:

UPDATE my_table
SET my_column = MAXIMUM(my_column - 10, 0);

回答by Mark Byers

Have a look at GREATEST and LEAST.

看看GREATEST 和 LEAST

UPDATE my_table
SET my_column = GREATEST(my_column - 10, 0);

回答by Donnie

You want the inline sql case:

你想要内联 sql case

set my_column = case when my_column - 10 > 0 then my_column - 10 else 0 end

max()is an aggregate function and gets the maximum of a row of a result set.

max()是一个聚合函数,获取结果集中一行的最大值。

Edit: oops, didn't know about greatestand leastin postgres. Use that instead.

编辑:哎呀,不知道greatestleast在 postgres 中。改用那个。