2012-06-28

TSQL - Lowest of two dates using arithmetic

You could create a UDF for this, and then nest calls to it in order to get the maximum of a collection of 3, 4, 5 or more fields.  Change the minus sign (big bold red below), to a plus sign, in order to retrieve the maximum of the two dates.


declare @val1 as date;
declare @val2 as date;

set @val1='2011-12-31';
set @val2='2012-06-27';

select
       DATEADD
       (
              d
              ,
              cast(
                     0.5
                     * (
                           (
                                  datediff(DAY,'1990-01-01',@val1)
                                  + datediff(DAY,'1990-01-01',@val2)
                           )
                           - ABS(
                                  datediff(DAY,'1990-01-01',@val1)
                                  - datediff(DAY,'1990-01-01',@val2)
                           )
                     )
                     as int
              )
              , cast('1990-01-01' as date)
       )
;

No comments:

Post a Comment