我想写一个这样的查询:

SELECT o.OrderId, MAX(o.NegotiatedPrice, o.SuggestedPrice)
FROM Order o

但这不是MAX函数的工作原理,对吧?它是一个聚合函数,因此它需要一个参数,然后返回所有行的MAX。

有人知道我的方法吗?


当前回答

为什么不尝试IIF功能(需要SQL Server 2012及更高版本)

IIF(a>b, a, b)

就是这样。

(额外提示:小心a或b是否为空,因为在这种情况下,>b的结果将为假。因此,如果任意一个为空,则返回结果为b)(同样根据系统设计,列为空也不是一个好的实践)

其他回答

如果你使用的是SQL Server 2008(或更高版本),那么这是更好的解决方案:

SELECT o.OrderId,
       (SELECT MAX(Price)
        FROM (VALUES (o.NegotiatedPrice),(o.SuggestedPrice)) AS AllPrices(Price))
FROM Order o

所有的信用和投票都应该去Sven对一个相关问题的答案,“多列的SQL MAX ?” 我说这是“最佳答案”,因为:

It doesn't require complicating your code with UNION's, PIVOT's, UNPIVOT's, UDF's, and crazy-long CASE statments. It isn't plagued with the problem of handling nulls, it handles them just fine. It's easy to swap out the "MAX" with "MIN", "AVG", or "SUM". You can use any aggregate function to find the aggregate over many different columns. You're not limited to the names I used (i.e. "AllPrices" and "Price"). You can pick your own names to make it easier to read and understand for the next guy. You can find multiple aggregates using SQL Server 2008's derived_tables like so: SELECT MAX(a), MAX(b) FROM (VALUES (1, 2), (3, 4), (5, 6), (7, 8), (9, 10) ) AS MyTable(a, b)

对于SQL Server 2012:

SELECT 
    o.OrderId, 
    IIF( o.NegotiatedPrice >= o.SuggestedPrice,
         o.NegotiatedPrice, 
         ISNULL(o.SuggestedPrice, o.NegiatedPrice) 
    )
FROM 
    Order o

我会使用kcrumley提供的解决方案 只需稍微修改它以处理null

create function dbo.HigherArgumentOrNull(@val1 int, @val2 int)
returns int
as
begin
  if @val1 >= @val2
    return @val1
  if @val1 < @val2
    return @val2

 return NULL
end

编辑 在Mark的评论后修改。正如他在3值逻辑x > NULL或x < NULL应该总是返回NULL。换句话说,未知的结果。

SELECT o.OrderId,   
--MAX(o.NegotiatedPrice, o.SuggestedPrice)  
(SELECT MAX(v) FROM (VALUES (o.NegotiatedPrice), (o.SuggestedPrice)) AS value(v)) as ChoosenPrice  
FROM Order o

试试这个。它可以处理2个以上的值

SELECT Max(v) FROM (VALUES (1), (2), (3)) AS value(v)