带日期条件逻辑的 CASE 表达式

CASE Expression with Dates conditional Logic

我在报表查询中有一个逻辑,它确定过去的天数,不包括周末。有 2 个可能的开始日期 - 原始接收日期或重新提交的日期(如果存在)。我可以使用以下 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] 之前,在这些情况下,即使 [ResubmitReceivedDate] 仍应使用 [OriginalReceivedDate]存在。

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

似乎最简单的解决方案就是添加另一个 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