具有日期条件逻辑的CASE表达式

时间:2015-01-14 17:02:24

标签: sql sql-server case

我在查询中有一个逻辑,用于确定通过的天数,不包括周末。有两种可能的开始日期 - 原始收货日期或重新提交日期(如果存在)。我可以使用以下CASE语句

正确计算
  CASE WHEN [ResubmitReceivedDate] IS NULL THEN
  (SELECT
        (DATEDIFF(dd, [OriginalReceivedDate] , [AnalysisDate]) + 1)
        -(DATEDIFF(wk,[OriginalReceivedDate] , [AnalysisDate]) * 2)
        -(CASE WHEN DATENAME(dw, [OriginalReceivedDate] ) = 'Sunday' THEN 1 ELSE 0 END)
        -(CASE WHEN DATENAME(dw, [AnalysisDate]) = 'Saturday' THEN 1 ELSE 0 END) 
    )
    ELSE
    (SELECT
        (DATEDIFF(dd, [ResubmitReceivedDate], [AnalysisDate]) + 1)
        -(DATEDIFF(wk, [ResubmitReceivedDate], [AnalysisDate]) * 2)
        -(CASE WHEN DATENAME(dw, [ResubmitReceivedDate]) = 'Sunday' THEN 1 ELSE 0 END)
        -(CASE WHEN DATENAME(dw, [AnalysisDate]) = 'Saturday' THEN 1 ELSE 0 END) 
    ) 

但是,有些情况下[AnalysisDate]位于[ResubmitReceivedDate]之前,在这些情况下,即使[OriginalReceivedDate]存在,仍应使用[ResubmitReceivedDate]

如何将此逻辑添加到上述CASE语句中?

1 个答案:

答案 0 :(得分:1)

似乎最简单的解决方案就是添加另一个When条件。像这样:

WHEN DateDiff(day, [ResubmitReceivedDate], [AnalysisDate]) > -1 THEN
    (Select
        (DATEDIFF(day, [OriginalReceivedDate] , [AnalysisDate]) + 1)
        -(DATEDIFF(week,[OriginalReceivedDate] , [AnalysisDate]) * 2)
        -(CASE WHEN DATENAME(weekday, [OriginalReceivedDate] ) = 'Sunday' THEN 1 ELSE 0 END)
        -(CASE WHEN DATENAME(weekday, [AnalysisDate]) = 'Saturday' THEN 1 ELSE 0 END)
    )

哪个会成为你的最终案例

Case
     WHEN [ResubmitReceivedDate] IS NULL THEN
        (Select
            (DATEDIFF(day, [OriginalReceivedDate] , [AnalysisDate]) + 1)
            -(DATEDIFF(week,[OriginalReceivedDate] , [AnalysisDate]) * 2)
            -(CASE WHEN DATENAME(weekday, [OriginalReceivedDate] ) = 'Sunday' THEN 1 ELSE 0 END)
            -(CASE WHEN DATENAME(weekday, [AnalysisDate]) = 'Saturday' THEN 1 ELSE 0 END)
        )
     WHEN DateDiff(day, [ResubmitReceivedDate], [AnalysisDate]) < -1 THEN
        (Select
            (DATEDIFF(day, [OriginalReceivedDate] , [AnalysisDate]) + 1)
            -(DATEDIFF(week,[OriginalReceivedDate] , [AnalysisDate]) * 2)
            -(CASE WHEN DATENAME(weekday, [OriginalReceivedDate] ) = 'Sunday' THEN 1 ELSE 0 END)
            -(CASE WHEN DATENAME(weekday, [AnalysisDate]) = 'Saturday' THEN 1 ELSE 0 END)
        )
    Else
        (SELECT
            (DATEDIFF(day, [ResubmitReceivedDate], [AnalysisDate]) + 1)
            -(DATEDIFF(week, [ResubmitReceivedDate], [AnalysisDate]) * 2)
            -(CASE WHEN DATENAME(weekday, [ResubmitReceivedDate]) = 'Sunday' THEN 1 ELSE 0 END)
            -(CASE WHEN DATENAME(weekday, [AnalysisDate]) = 'Saturday' THEN 1 ELSE 0 END) 
        )
End