I have a table that has 38 columns that are all datetime data type. I want to query the column name that has the max date in each row.
I have figured out how to determine the max date of each row, but I'm not sure how to query which column it came from.
IF OBJECT_ID('tempdb..#MaxDates') IS NOT NULL DROP TABLE #MaxDates SELECT [ColumnOne], Max( StartDate) as MaxEffDate Into #MaxDates FROM dbo.DatabaseName group by [ColumnOne] Select a.[ColumnOne], StartDate, (SELECT MAX(LastUpdateDate) FROM (VALUES (case when (ColumnTwo) < '9999-12-31' then (ColumnTwo) else '1900-01-01' end) ) AS UpdateDate(LastUpdateDate) ) AS LastUpdateDate From dbo.DatabaseName a inner join #MaxDates on a.[ColumnOne] =#MaxDates.[ColumnOne] and a.StartDate = #MaxDates.MaxEffDate order by a.[ColumnOne] asc I expect the following result-
ColumnOne, StartDate, LastUpdateDate, LastUpdateDateColumnName