Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In SQL Server, how do I get the latest dates with multiple columns of dates?

This feels like it should be an easy one. How do I get the latest of 3 dates that are in different columns

DROP TABLE #dates
CREATE TABLE #dates (mykey CHAR(10), date1 DATETIME, date2 DATETIME, date3 DATETIME)
INSERT #dates VALUES ('Key1', '1/1/2015', '2/1/2015', '3/1/2105')
INSERT #dates VALUES ('Key2', '1/2/2015', '4/2/2015', '3/2/2105')
INSERT #dates VALUES ('Key3', '1/3/2016', '4/3/2015', '3/3/2105')

select mykey, ?? AS 'Latest Date' from #dates

I would like the result to be:

mykey       Latest Date
Key1        2105-03-01 00:00:00.000
Key2        2015-04-02 00:00:00.000
Key3        2016-01-03 00:00:00.000
like image 822
JeffJak Avatar asked Dec 21 '15 21:12

JeffJak


People also ask

How do I get the latest date record in SQL?

From table_name Order By date_column Desc; Now, let's use the given syntax to select the last 10 records from our sample table. Select * From SampleTable Order By [Date] Desc; After executing the above example, the server will return the records in such a way that the records with the latest dates appear at the top.

How do I get the date sequence in SQL?

To generate a date sequence, you can use the number sequence technique and the T-SQL function DATEADD().

How can I get data between specific dates in SQL?

SELECT * FROM ATM WHERE TRANSACTION_TIME BETWEEN '2005-02-28 21:00:00' AND '2008-12-25 00:00:00';


1 Answers

Probably the easiest way in SQL Server is to use cross apply:

select d.*, m.maxdate
from #dates d cross apply
     (select max(dte) as maxdate
      from (values (date1), (date2), (date3)) as v(dte)
     )  m;
like image 53
Gordon Linoff Avatar answered Nov 14 '22 22:11

Gordon Linoff