This is my query:
declare @t table (date1 date,date2 date,date3 date) insert into @t values ('2019-01-01','2019-01-20','2019-02-10') insert into @t values (null,null,'2019-02-01') insert into @t values (null,'2019-02-01','2019-02-02')
My expected output is:
2019-02-10 2019-02-01 2019-02-02
I tried to use coalesce like :
select coalesce(date1,date2,date3) as maxdate from @t
I know coalesce returns first not null value. So what I can do to get my desired result.
Advertisement
Answer
coalesce()
has nothing to do with this. Unfortunately, SQL Server does not support greatest()
. But you can use apply
:
select t.*, m.max_date from @t t cross apply (select max(dte) as max_date from (values (t.date1), (t.date2), (t.date3)) v(dte) ) m;
The max()
ignores NULL
values, so this does what you expect.
Here is a db<>fiddle.