复杂的CASE表达代码

时间:2018-05-31 17:49:29

标签: sql sql-server

我有一个我需要修改的现有案例陈述,这给我带来了一些麻烦。现有代码:

CASE WHEN (DATEDIFF(Day, MAX(ContDataTranDate), ContDataEnd) + 1)
-(DATEDIFF(wk, MAX(ContDataTranDate), ContDataEnd) * 2)  
-(CASE WHEN DATENAME(dw, MAX(ContDataTranDate)) = 'Sunday' THEN 1 ELSE 0 END)
-(CASE WHEN DATENAME(dw, ContDataEnd) = 'Saturday' THEN 1 ELSE 0 END) -1  = 1 THEN 1 ELSE 0 END [Shipped1Day]   

我需要补充的内容:
我有2个新列,SOFReleaseDateNameSOFReleaseDateValue 我需要更改现有语句,以便在当前使用SOFReleaseDateName ELSE的计算中SOFReleaseDateValue不为空时使用ContDataTranDate而不是ContDataTranDate时使用{{1} }。我尝试了很多不同的方法 ContDataTranDate也是日期。

2 个答案:

答案 0 :(得分:0)

只需在您检查SOFReleaseDateName

的前面添加一个新的case语句
CASE WHEN SOFReleaseDateName IS NOT NULL THEN
   CASE WHEN (DATEDIFF(Day, MAX(SOFReleaseDateValue ), ContDataEnd) + 1)
            -(DATEDIFF(wk, MAX(SOFReleaseDateValue ), ContDataEnd) * 2)  
            -(CASE WHEN DATENAME(dw, MAX(SOFReleaseDateValue )) = 'Sunday' THEN 1 ELSE 0 END)
            -(CASE WHEN DATENAME(dw, ContDataEnd) = 'Saturday' THEN 1 ELSE 0 END) -1  = 1 
        THEN 1 
        ELSE 0
    END
WHEN
    (DATEDIFF(Day, MAX(ContDataTranDate), ContDataEnd) + 1)
    -(DATEDIFF(wk, MAX(ContDataTranDate), ContDataEnd) * 2)  
    -(CASE WHEN DATENAME(dw, MAX(ContDataTranDate)) = 'Sunday' THEN 1 ELSE 0 END)
    -(CASE WHEN DATENAME(dw, ContDataEnd) = 'Saturday' THEN 1 ELSE 0 END) -1  = 1 

    THEN 1 
    ELSE 0 
END [Shipped1Day] 

SOFReleaseDateName IS NOT NULL案例

之后,您可能需要ELSE而不是WHEN
CASE WHEN SOFReleaseDateName IS NOT NULL THEN
    CASE WHEN (DATEDIFF(Day, MAX(SOFReleaseDateValue ), ContDataEnd) + 1)
            -(DATEDIFF(wk, MAX(SOFReleaseDateValue ), ContDataEnd) * 2)  
            -(CASE WHEN DATENAME(dw, MAX(SOFReleaseDateValue )) = 'Sunday' THEN 1 ELSE 0 END)
            -(CASE WHEN DATENAME(dw, ContDataEnd) = 'Saturday' THEN 1 ELSE 0 END) -1  = 1 
        THEN 1 
        ELSE 0
    END
ELSE
     CASE WHEN (DATEDIFF(Day, MAX(ContDataTranDate), ContDataEnd) + 1)
            -(DATEDIFF(wk, MAX(ContDataTranDate), ContDataEnd) * 2)  
            -(CASE WHEN DATENAME(dw, MAX(ContDataTranDate)) = 'Sunday' THEN 1 ELSE 0 END)
            -(CASE WHEN DATENAME(dw, ContDataEnd) = 'Saturday' THEN 1 ELSE 0 END) -1  = 1 
        THEN 1 
        ELSE 0 
    END
END [Shipped1Day]  

答案 1 :(得分:0)

CASE WHEN (DATEDIFF(Day, MAX(case when SOFReleaseDateName is not null then SOFReleaseDateValue else ContDataTranDate end), ContDataEnd) + 1)
-(DATEDIFF(wk, MAX(case when SOFReleaseDateName is not null then SOFReleaseDateValue else ContDataTranDate end), ContDataEnd) * 2)  
-(CASE WHEN DATENAME(dw, MAX(case when SOFReleaseDateName is not null then SOFReleaseDateValue else ContDataTranDate end)) = 'Sunday' THEN 1 ELSE 0 END)
-(CASE WHEN DATENAME(dw, ContDataEnd) = 'Saturday' THEN 1 ELSE 0 END) -1  = 1 THEN 1 ELSE 0 END [Shipped1Day]