Is there a Max function in SQL Server that takes two values like Math.Max in .NET?(SQL Server 中是否有一个 Max 函数,它采用两个值,如 .NET 中的 Math.Max?)
问题描述
我想写一个这样的查询:
I want to write a query like this:
SELECT o.OrderId, MAX(o.NegotiatedPrice, o.SuggestedPrice)
FROM Order o
但这不是 MAX
函数的工作原理,对吧?它是一个聚合函数,因此它需要一个参数,然后返回所有行的 MAX.
But this isn't how the MAX
function works, right? It is an aggregate function so it expects a single parameter and then returns the MAX of all rows.
有谁知道如何按照我的方式来做?
Does anyone know how to do it my way?
推荐答案
如果你想有一个类似于你的例子的语法,你需要制作一个 User-Defined Function
,但你能做到吗?就像其他人所说的那样,你想用 CASE
语句相当容易地内联.
You'd need to make a User-Defined Function
if you wanted to have syntax similar to your example, but could you do what you want to do, inline, fairly easily with a CASE
statement, as the others have said.
UDF
可能是这样的:
create function dbo.InlineMax(@val1 int, @val2 int)
returns int
as
begin
if @val1 > @val2
return @val1
return isnull(@val2,@val1)
end
...你会这样称呼它...
... and you would call it like so ...
SELECT o.OrderId, dbo.InlineMax(o.NegotiatedPrice, o.SuggestedPrice)
FROM Order o
这篇关于SQL Server 中是否有一个 Max 函数,它采用两个值,如 .NET 中的 Math.Max?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:SQL Server 中是否有一个 Max 函数,它采用两个值,如 .NET 中的 Math.Max?


基础教程推荐
- MySQL根据从其他列分组的值,对两列之间的值进行求和 2022-01-01
- MySQL 5.7参照时间戳生成日期列 2022-01-01
- 带更新的 sqlite CTE 2022-01-01
- ORA-01830:日期格式图片在转换整个输入字符串之前结束/选择日期查询的总和 2021-01-01
- while 在触发器内循环以遍历 sql 中表的所有列 2022-01-01
- 带有WHERE子句的LAG()函数 2022-01-01
- 使用 VBS 和注册表来确定安装了哪个版本和 32 位 2021-01-01
- 从字符串 TSQL 中获取数字 2021-01-01
- CHECKSUM 和 CHECKSUM_AGG:算法是什么? 2021-01-01
- 如何在 CakePHP 3 中实现 INSERT ON DUPLICATE KEY UPDATE aka upsert? 2021-01-01