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
How to get min/max of two integers in Postgres/SQL?
提问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.
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 greatest
and least
in postgres. Use that instead.
编辑:哎呀,不知道greatest
和least
在 postgres 中。改用那个。