在SQL中,是否存在非聚合最小/最大运算符

时间:2022-06-01 19:47:29

Is there something like

是否有类似的东西

select max(val,0)
from table

I'm NOT looking to find the maximum value of the entire table

我不是要找到整个表的最大值

There has to be an easier way than this right?

必须有一个比这更简单的方法吗?

select case when val > 0 then val else 0 end
from table

EDIT: I'm using Microsoft SQL Server

编辑:我正在使用Microsoft SQL Server

4 个解决方案

#1


9  

Functions GREATEST and LEAST are not SQL standard but are in many RDBMSs (e.g., Postgresql). So

函数GREATEST和LEAST不是SQL标准,但在许多RDBMS中(例如,Postgresql)。所以

SELECT GREATEST(val, 0) FROM mytable;

#2


1  

Not in SQL per se. But many database engines define a set of functions you can use in SQL statements. Unfortunately, they generally use different names and arguments list.

不是SQL本身。但是许多数据库引擎定义了一组可以在SQL语句中使用的函数。不幸的是,它们通常使用不同的名称和参数列表。

In MySQL, the function is GREATEST. In SQLite, it's MAX (it works differently with one parameter or more).

在MySQL中,该功能非常棒。在SQLite中,它是MAX(它对一个参数或更多参数的工作方式不同)。

#3


0  

Make it a set based JOIN?

使它成为一个基于JOIN的集合?

SELECT
   max(val)
FROM
(
select val
from table
UNION ALL
select 0
) foo

This avoids a scalar udf suggested in the other question which may suit better

这避免了另一个问题中建议的标量udf,它可能更适合

#4


-3  

What you have in SQL is not even valid SQL. That's not how MAX works in SQL. In T-SQL the MAX aggregates over a range returning the maximum value. What you want is a simply the greater value of two.

SQL中的内容甚至不是有效的SQL。这不是MAX在SQL中的工作方式。在T-SQL中,MAX在返回最大值的范围内聚合。你想要的只是两个人的更大价值。

Read this for more info:

阅读本文了解更多信息:

Is there a Max function in SQL Server that takes two values like Math.Max in .NET?

SQL Server中是否有一个Max函数,它在.NET中采用Math.Max这两个值?

#1


9  

Functions GREATEST and LEAST are not SQL standard but are in many RDBMSs (e.g., Postgresql). So

函数GREATEST和LEAST不是SQL标准,但在许多RDBMS中(例如,Postgresql)。所以

SELECT GREATEST(val, 0) FROM mytable;

#2


1  

Not in SQL per se. But many database engines define a set of functions you can use in SQL statements. Unfortunately, they generally use different names and arguments list.

不是SQL本身。但是许多数据库引擎定义了一组可以在SQL语句中使用的函数。不幸的是,它们通常使用不同的名称和参数列表。

In MySQL, the function is GREATEST. In SQLite, it's MAX (it works differently with one parameter or more).

在MySQL中,该功能非常棒。在SQLite中,它是MAX(它对一个参数或更多参数的工作方式不同)。

#3


0  

Make it a set based JOIN?

使它成为一个基于JOIN的集合?

SELECT
   max(val)
FROM
(
select val
from table
UNION ALL
select 0
) foo

This avoids a scalar udf suggested in the other question which may suit better

这避免了另一个问题中建议的标量udf,它可能更适合

#4


-3  

What you have in SQL is not even valid SQL. That's not how MAX works in SQL. In T-SQL the MAX aggregates over a range returning the maximum value. What you want is a simply the greater value of two.

SQL中的内容甚至不是有效的SQL。这不是MAX在SQL中的工作方式。在T-SQL中,MAX在返回最大值的范围内聚合。你想要的只是两个人的更大价值。

Read this for more info:

阅读本文了解更多信息:

Is there a Max function in SQL Server that takes two values like Math.Max in .NET?

SQL Server中是否有一个Max函数,它在.NET中采用Math.Max这两个值?