This feels like it should be an easy one. How do I get the latest dates that are in different columns
DROP TABLE #indebtedness CREATE TABLE #indebtedness (call_case CHAR(10), date1 DATETIME, date2 DATETIME, date3 DATETIME) INSERT #indebtedness VALUES ('Key1', '2019-10-30', '2019-11-30', '2019-10-25') INSERT #indebtedness VALUES ('Key2', '2019-10-20', '2019-10-30', '2019-10-15') INSERT #indebtedness VALUES ('Key3', '2019-11-11', '2019-10-29', '2019-10-30') INSERT #indebtedness VALUES ('Key4', null , '2019-10-29', '2019-10-13') select call_case, ?? AS 'Latest Date' from #indebtedness
I would like the result to be:
call_case Latest Date Key1 2019-11-30 Key2 2019-10-30 Key3 2019-11-11 Key4 2019-10-29
Advertisement
Answer
Use a CASE
expression:
SELECT call_case, CASE WHEN date1 > date2 AND date1 > date3 THEN date1 WHEN date2 > date3 THEN date2 ELSE date3 END AS [Latest Date] FROM #indebtedness;
Note that some databases, such as MySQL, SQL Server, and SQLite, support a scalar greatest function. SQL Server does not, so we can use a CASE
expression as a workaround.
Edit:
It appears that in your actual table, one or more of the three date columns could have NULL
values. We can adapt the above query as follows:
SELECT call_case, CASE WHEN (date1 > date2 OR date2 IS NULL) AND (date1 > date3 OR date3 IS NULL) THEN date1 WHEN date2 > date3 OR date3 IS NULL THEN date2 ELSE date3 END AS [Latest Date] FROM #indebtedness;