Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the Latest date from the Three columns [duplicate]

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.

like image 796
user3619447 Avatar asked May 26 '14 06:05

user3619447


People also ask

How do you find the current date in Excel with multiple criteria?

To get the latest date with the criteria, you can apply this array formula: =MAX(IF($A$2:$A$16="Office Tab",$B$2:$B$16)), and remember to press Ctrl + Shift + Enter keys together to get the correct result.


4 Answers

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

like image 167
potashin Avatar answered Nov 15 '22 08:11

potashin


Try using CASE:

SELECT ID,
       CASE WHEN Date1>=Date2 AND  Date1>=Date3 THEN Date1
            WHEN Date2>=Date1 AND  Date2>=Date3 THEN Date2
            WHEN Date3>=Date1 AND  Date3>=Date2 THEN Date3
      END AS GreatestDate
FROM TableName
like image 36
Raging Bull Avatar answered Nov 15 '22 07:11

Raging Bull


SELECT CASE WHEN date1 > date2 AND date1 > date3 THEN date1
            WHEN date2 > date3 THEN date2
            ELSE date3 END MaxDate
FROM TableName
like image 22
Nithin Gangadharan Avatar answered Nov 15 '22 07:11

Nithin Gangadharan


Please try using UNPIVOT

SELECT MAX(MaxDt) MaxDt
   FROM tbl 
UNPIVOT
   (MaxDt FOR E IN 
      (Date1, Date2, Date3)
)AS unpvt;
like image 43
TechDo Avatar answered Nov 15 '22 08:11

TechDo