从三列中获取最新日期

时间:2014-05-26 06:40:44

标签: sql sql-server sql-server-2008 tsql

ID     Date1           Date2            Date3   
158    5/3/13 15:11    2/20/13 11:38    2/20/13 11:38

我想从这三列中获取最新日期。

7 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分:1)

尝试使用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

答案 2 :(得分:1)

SELECT CASE WHEN date1 > date2 AND date1 > date3 THEN date1
            WHEN date2 > date3 THEN date2
            ELSE date3 END MaxDate
FROM TableName

答案 3 :(得分:1)

请尝试使用UNPIVOT

SELECT MAX(MaxDt) MaxDt
   FROM tbl 
UNPIVOT
   (MaxDt FOR E IN 
      (Date1, Date2, Date3)
)AS unpvt;

答案 4 :(得分:0)

这可能会对你有所帮助

 select case when Date1 > Date 2 then case when Date1 > Date3 then Date1 end
        when Date2 > Date3 then Date2   
       else  Date3 from <yortable>

答案 5 :(得分:0)

SELECT
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
    ELSE Date1
END AS MostRecentDate

OR

SELECT  MAX(date_columns) AS max_date
       FROM    
       ( 
          (SELECT date1 AS date_columns FROM tablename)
          UNION
          (SELECT date2 AS date_columns FROM tablename)
          UNION
          (SELECT date3 AS date_columns FROM tablename)
       ) AS date_query

答案 6 :(得分:0)

试试这个......:)

select top 1 a.date from
(
select Date1 as date from table_name where Id='158'
union
select Date2 as date from table_name where Id='158'
union
select Date3 as date from table_name where Id='158'
)a
order by a.date DESC;