SQL Server中是否有一个Max函数采用两个值,如.NET中的Math.Max? [英] Is there a Max function in SQL Server that takes two values like Math.Max in .NET?
本文介绍了SQL Server中是否有一个Max函数采用两个值,如.NET中的Math.Max?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想这样写一个查询:
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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文