我正在比较两个日期,并试图确定两个日期的最大值.空日期将被视为小于有效日期.我正在使用以下案例陈述,它有效 - 但感觉非常低效和笨重.有没有更好的办法?
update @TEMP_EARNED
set nextearn = case when lastoccurrence is null and lastearned is null then null
when lastoccurrence is null then lastearned
when lastearned is null then lastoccurrence
when lastoccurrence > lastearned then lastoccurrence
else lastearned end;
Run Code Online (Sandbox Code Playgroud)
(这是在MS SQL 2000,FYI.)
select c1, c2,
case when c1 > c2 then c1 else coalesce(c2,c1) end as max
from twocol;
+------+------+------+
| c1 | c2 | max |
+------+------+------+
| NULL | NULL | NULL |
| NULL | 2 | 2 |
| 1 | NULL | 1 |
| 1 | 2 | 2 |
| NULL | NULL | NULL |
| 2 | NULL | 2 |
| NULL | 1 | 1 |
| 2 | 1 | 2 |
+------+------+------+
Run Code Online (Sandbox Code Playgroud)
为什么这样做?如果两个操作数都不为null,那么我们得到一个"正常"比较:当c1> c2时为"then"分支,当c1 <= c2时为else分支.
在"else"分支上,我们调用coalesce,但由于它的第一个参数是非null c2,我们返回c2.
.
但是如果任一操作数为null,则测试结果c1 > c2为false,然后返回coalesce( c2, c1 ).
如果空操作数是c1,我们得到c2,这是我们想要的,因为我们(对于这个问题)调用null是"小于"任何非空值.
如果空操作数是c2,我们得到c1.那很好,因为c1要么不为空,因此(对于这个问题)"大于"null c2,或者......
如果两个操作数都为null,我们得到c1,但是我们得到的并不重要,因为两者都是null.
另一个优点是,这个成语适用于任何类型的
operator >作品,没有进一步的思考或细节.