最小和最多两列

时间:2017-02-27 11:49:00

标签: sql-server

我想找到2列中存在的最小值,2列中存在最大值 EX:A:2 3 4     B:5 6 7

Ans应该是2分钟,最多7分钟。 A和B是同一表中的列。  min()内置函数不存在。

5 个答案:

答案 0 :(得分:3)

我认为最简单的方法是apply

select min(x.val), max(x.val)
from t cross apply
     (select val
      from (values (t.col1), (t.col2)) v(val)
     ) x;

在运行聚合函数之前,cross apply只是将值展开为单个列。

答案 1 :(得分:2)

你可以选择:

limit

答案 2 :(得分:0)

自包含的例子。

declare @t table(a int, b int)
insert into @t values(2,5)
insert into @t values(3,6)
insert into @t values(4,7)

select min(a) as a,max(b) as b from @t

--if for some reason min() and max() are 'not available' (???)
select
  (select top 1 a from @t order by a asc) as a
 ,(select top 1 b from @t order by a desc) as b

答案 3 :(得分:0)

如果存在合适的索引,那么首先在列A和B上独立地执行MIN / MAX可能更有效,因为它希望在这些列上使用一些搜索到适当的索引:

[ActionName("")]

答案 4 :(得分:-1)

您可以使用Max和Min函数来确定该列的最大n min值。

  Select Min(A),Max(B) from Table