在两列之间选择最新日期 [英] Selecting most recent date between two columns
问题描述
如果我有一个表(除其他列外)有两个DATETIME列,我该如何从这两列中选择最近日期。
If I have a table that (among other columns) has two DATETIME columns, how would I select the most recent date from those two columns.
示例:
ID Date1 Date2
1 1/1/2008 2/1/2008
2 2/1/2008 1/1/2008
3 1/10/2008 1/10/2008
如果我希望我的结果看起来像
If I wanted my results to look like
ID MostRecentDate
1 2/1/2008
2 2/1/2008
3 1/10/2008
是否有一种简单的方法可以使我明显地忽略掉?我知道我可以执行子查询和case语句,甚至可以在sql server中编写一个函数来处理它,但是我脑子里已经有了一个内置的max-compare类型函数,我只是忘记了。
Is there a simple way of doing this that I am obviously overlooking? I know I can do subqueries and case statements or even write a function in sql server to handle it, but I had it in my head that there was a max-compare type function already built in that I am just forgetting about.
推荐答案
案例是恕我直言,您最好的选择:
CASE is IMHO your best option:
SELECT ID,
CASE WHEN Date1 > Date2 THEN Date1
ELSE Date2
END AS MostRecentDate
FROM Table
如果其中一列为空,则只需将其包含在 COALESCE
:
.. COALESCE(Date1, '1/1/1973') > COALESCE(Date2, '1/1/1973')
这篇关于在两列之间选择最新日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!