Get the Latest date from the Three columns
sql, sql-server, sql-server-2008, t-sql
Solution
SELECT CASE WHEN Date1 IS NOT NULL
AND Date1>=COALESCE(Date2,CAST('0001-01-01 00:00' AS DATETIME2))
AND Date1>=COALESCE(Date3,CAST('0001-01-01 00:00' AS DATETIME2)) THEN Date1
WHEN Date2 IS NOT NULL
AND Date2>=COALESCE(Date1,CAST('0001-01-01 00:00' AS DATETIME2))
AND Date2>=COALESCE(Date3,CAST('0001-01-01 00:00' AS DATETIME2)) THEN Date2
WHEN Date3 IS NOT NULL
AND Date3>=COALESCE(Date1,CAST('0001-01-01 00:00' AS DATETIME2))
AND Date3>=COALESCE(Date2,CAST('0001-01-01 00:00' AS DATETIME2)) THEN Date3
END AS latest
FROM t1
Example
Problem
``` ID Date1 Date2 Date3 158 5/3/13 15:11 2/20/13 11:38 2/20/13 11:38 ``` I want to get the latest date from this three columns.