I have a table with several date fields. I need to get a derived field that is the oldest date of 3 particular fields. I have to do this for 4 different date sets.
Asked
Active
Viewed 7,167 times
1 Answers
6
One simple way is to use a case
expressions:
select case when Date1 > Date2 and Date1 > Date3 then
Date1
when Date2 > Date3 and Date2 > Date1 then
Date2
else
Date3
end As TheDate
from tableName
Though this is quite simple, it tends to get really cumbersome really fast, if you have more columns. Another option would be to use the values
clause, like this:
select (
select max(date)
from (values (date1), (date2), (date3))v(date)
)
from tableName
This also enables you to get min value easily.

Zohar Peled
- 79,642
- 10
- 69
- 121
-
You have to add something on the ELSE for Date 2 vs Date 3 – Juan Carlos Oropeza Feb 04 '19 at 20:20
-
@JuanCarlosOropeza corrected. – Zohar Peled Feb 04 '19 at 20:26
-
Well you change it, did you saw a problem with the previous one? – Juan Carlos Oropeza Feb 04 '19 at 20:28
-
You cant have multiple else in a CASE. Check my edit – Juan Carlos Oropeza Feb 04 '19 at 20:30
-
@JuanCarlosOropeza Yeah, I've noticed the typo. thanks for the fix but I was just editing in the other option :-) – Zohar Peled Feb 04 '19 at 20:31
-
I know dont worry, that is why I let you know in case you still were editing – Juan Carlos Oropeza Feb 04 '19 at 20:32
-
Oooo. I like the last one! Never saw the values clause. Will try in the morning and report back. – shorton Feb 05 '19 at 00:59
-
1[Table Value Constructor](https://learn.microsoft.com/en-us/sql/t-sql/queries/table-value-constructor-transact-sql?view=sql-server-2017) – Zohar Peled Feb 05 '19 at 04:43
-
3I had some trouble with the syntax btu got it to work from an example in the other thread marked as a dup. SELECT [Other Fields], (SELECT Max(v) FROM (VALUES (date1), (date2), (date3),...) AS value(v)) as [MaxDate] FROM [YourTableName] – shorton Feb 05 '19 at 14:43
-
If Date2 or Date3 as NULL though this won't work. I got round this by using OR instead of AND. – Mike May 12 '20 at 11:41