sql 查找 N 个值中最小值的服务器函数

sql server function to find minimum of N number of values

我想在 select 语句中找到最小值; 假设有一个叫做 findMin 的函数,

select
   select min from findMin(firstDate,secondDate,thirdDate,....NDate),
   firstDate,
   secondDate,
   thirdDate,
   .... (having N number of dates)
from
   dateTable

我在 sql 服务器 2008 R2 中编写 findMin 函数时遇到问题。

有帮助吗?

谢谢

SQL 服务器不支持 least()greatest()(唉)。如果值从不 NULL,以下逻辑很麻烦,但可以满足五个日期的要求:

select (case when date1 <= date2 and date1 <= date3 and date1 <= date4 and date1 <= date5
             then date1
             when date2 <= date3 and date2 <= date4 and date2 <= date5
             then date2
             when date3 <= date4 and date3 <= date5
             then date3
             when date4 <= date5
             then date4
             else date5
         end)

这可以很容易地推广到更多日期。它只是需要更多的逻辑。

还有另一种选择,即取消数据透视然后重新聚合。但是,这比仅在一行中执行操作要昂贵得多。

您可以使用它来查找最早的日期:

SELECT
   MinDate.mDate,
   dt.firstDate,
   dt.secondDate,
   dt.thirdDate
FROM
   dateTable dt
outer apply
(
  SELECT min(mDate)
  FROM (values(firstDate), (secondDate), 
       (ThirdDate), (FourthDate)) x(mDate)
) MinDate