2012-06-28

TSQL - Greatest of two dates using arithmetic


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