如何从两个字段中提取最新的日期

时间:2013-08-16 17:41:30

标签: tsql sql-server-2012-express

我有一个包含两个截止日期字段的表。有时它们都可以匹配,有时其中一个是空白的,有时其中一个比另一个大。我需要如何将最新的截止日期从两个字段中的一个字段中拉出来。字段是PBDUE和XDCURDT,它们都是表中的日期时间。

2 个答案:

答案 0 :(得分:1)

假设两列都是日期(日期/日期时间等),当您说空白时,您的意思是NULL

SELECT CASE WHEN PBDUE >= XDCURDT THEN PBDUE ELSE XDCURDT END DUEDT
FROM (
    SELECT MAX(PBDUE) PBDUE, MAX(XDCURDT) XDCURDT FROM someTable
) t

内部查询计算每列的最大(最近)值,外部查询返回最大值(如果两者相等,则返回PBDUE。)

答案 1 :(得分:0)

DECLARE @x TABLE(ID INT,PBDUE DATE, XDCURDT DATE);

INSERT @x VALUES
(1,'2013-01-01','2012-01-01'), -- PBDUE greater
(2,'2010-01-01','2011-01-01'), -- XDCURDT greater
(3,NULL,'2009-01-01'), -- PBDUE "blank"
(4,'2008-01-01',NULL); -- XDCURDT "blank"

-- if you want one max date per row:

SELECT ID, MostCurrentDate = CASE
  WHEN PBDUE >= COALESCE(XDCURDT, '1900-01-01') THEN PBDUE
  WHEN XDCURDT >= COALESCE(PBDUE, '1900-01-01') THEN XDCURDT
  -- might want an ELSE if you don't want NULL
  -- when both values are NULL
  END
FROM @x
ORDER BY ID;

-- if you want one max date for the whole table:

SELECT MostCurrentDate = MAX(d) FROM (SELECT CASE
  WHEN PBDUE >= COALESCE(XDCURDT, '1900-01-01') THEN PBDUE
  WHEN XDCURDT >= COALESCE(PBDUE, '1900-01-01') THEN XDCURDT
  END
FROM @x) AS c(d);

结果:

ID   MostCurrentDate
--   ---------------
1    2013-01-01
2    2011-01-01
3    2009-01-01
4    2008-01-01

MostCurrentDate
---------------
2013-01-01