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
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.
To generate a date sequence, you can use the number sequence technique and the T-SQL function DATEADD().
SELECT * FROM ATM WHERE TRANSACTION_TIME BETWEEN '2005-02-28 21:00:00' AND '2008-12-25 00:00:00';
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With