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.
有人知道我的方法吗?
推荐答案
如果你想拥有与你的示例类似的语法,你需要创建一个 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?
基础教程推荐
- 如何根据该 XML 中的值更新 SQL 中的 XML 2021-01-01
- 二进制文件到 SQL 数据库 Apache Camel 2021-01-01
- mysql选择动态行值作为列名,另一列作为值 2021-01-01
- 在 MySQL 中:如何将表名作为存储过程和/或函数参数传递? 2021-01-01
- oracle区分大小写的原因? 2021-01-01
- 什么是 orradiag_<user>文件夹? 2022-01-01
- 在多列上分布任意行 2021-01-01
- MySQL 中的类型:BigInt(20) 与 Int(20) 2021-01-01
- 表 './mysql/proc' 被标记为崩溃,应该修复 2022-01-01
- 如何在 SQL 中将 Float 转换为 Varchar 2021-01-01
