案例陈述比较多个日期

时间:2015-09-10 21:25:53

标签: sql-server-2008 case multiple-conditions

我已经阅读了更多关于这个问题的问题,然而我在这件事上承认,但是,我从这里找到的答案中尝试的所有问题仍然失败。所以我们走了......

我正在尝试比较多个表中的多个日期以查找最近的日期。查询中的连接工作正常,因为我正在进行其他比较并且它们工作正常。但是,每当我尝试运行这种情况时,即使条件得到满足,我也没有语法错误或任何它只是落入ELSE。这是在SQL Server 2008R2上。

代码:

SELECT
[OTHER COLUMNS],
'MOST_RECENT_DATE' = Case
    WHEN A.Date > B.Date AND A.Date > C.Date AND A.Date > D.Date THEN convert(varchar, A.Date,30)
    WHEN B.Date > A.Date AND B.Date > C.Date AND B.Date > D.Date THEN convert(varchar, B.Date,30)
    WHEN C.Date > A.Date AND C.Date > B.Date AND C.Date > D.Date THEN convert(varchar, C.Date,30)
    WHEN D.Date > A.Date AND D.Date > B.Date AND D.Date > C.Date THEN convert(varchar, D.Date,30)
    ELSE 'ATTENTION'
END
FROM TABLE E
LEFT JOIN TABLE A ON E.other = A.other
LEFT JOIN TABLE B ON E.other = B.other
LEFT JOIN TABLE C ON E.other = C.other
LEFT JOIN TABLE D ON E.other = D.other

当我进行单一比较时,它会起作用并返回日期,即。

CASE
    WHEN A.Date > B.Date THEN CONVERT(varchar,A.Date,30)
    ELSE 'WHATEVER'
END

所以问题必须在于多重比较,我可能只是盯着这个很长时间,需要走开但我不能为我的生活弄清楚为什么这会落到别的时候我知道情况已经满足。

我们非常感谢您提出的想法和考虑因素。如果有人想了解更多信息,或者我需要让自己更清楚,请告诉我。

1 个答案:

答案 0 :(得分:1)

考虑以下表格设计:

create table test1 (id int, date1 date);
insert into test1 values (1, '2015-04-04'), (2, '2015-04-04');

create table test2 (id int, date2 date);
insert into test2 values (1, '2015-04-05'), (2, NULL);

此查询将生成ID 1的预期结果,但ID 2会产生意外结果。

select *, 

case 
when test1.date1 < test2.date2 then 'test1 is smaller' 
else 'test1 is not smaller' 
end as comment

from test1
inner join test2 on test1.id = test2.id;

-- Result
id  date1       id  date2      comment
1   2015-04-04  1   2015-04-05 test1 is smaller
2   2015-04-04  2   null       test1 is not smaller

请注意,在评估id {2}的CASE语句时,控件会跳转到THEN语句的CASE部分。

您可以通过多种方式重写CASE语句以考虑NULL值。其中一种方法是将比较默认为远在过去的某一天,如下所示:

CASE
WHEN A.Date > COALESCE(B.Date, '1900-01-01) 
     AND A.Date > COALESCE(C.Date, '1900-01-01') 
     AND A.Date > COALESCE(D.Date, '1900-01-01') 
     THEN convert(varchar, A.Date,30)
WHEN ....
ELSE 'ATTENTION'
相关问题