我有两个日期计算如下:
CASE WHEN FinalApprovalDt is not null and mf.IncomingTocontrol = 1 THEN DATEDIFF ( SECOND , ManualDecisionDt , lastChangesByAgentDt) END AS M_ttp
CASE WHEN FinalApprovalDt is not null and mf.IncomingTocontrol = 0 and ContractPayoutAmt > 0 THEN DATEDIFF ( SECOND , SystemDecisionDt , lastChangesByAgentDt) END AS A_ttp
我需要将这两个的总量设置为秒,然后计算AVG,但是在以下情况下我得到NULL:
(Case When FinalApprovalDt is not null and mf.IncomingTocontrol = 1 and ContractPayoutAmt > 0 then DATEDIFF ( SECOND , ManualDecisionDt , lastChangesByAgentDt) End +
Case When FinalApprovalDt is not null and mf.IncomingTocontrol = 0 and ContractPayoutAmt > 0 then DATEDIFF ( SECOND , SystemDecisionDt , lastChangesByAgentDt) End ) As Total_TTP,
怎么了?
在该查询中有两个矛盾的情况,并且在不满足条件时您不处理案例。基于mf.IncomingTocontrol
,第一个或第二个案例将为NULL,而NULL + Anything始终为NULL
您应该在每个CASE中放置ELSE块:
(
Case When FinalApprovalDt is not null and mf.IncomingTocontrol = 1 and ContractPayoutAmt > 0
then DATEDIFF ( SECOND , ManualDecisionDt , lastChangesByAgentDt)
ELSE 0 End
+
Case When FinalApprovalDt is not null and mf.IncomingTocontrol = 0 and ContractPayoutAmt > 0
then DATEDIFF ( SECOND , SystemDecisionDt , lastChangesByAgentDt)
ELSE 0 End
) As Total_TTP,
如果为NULL,则使用COALESCE包装值
(
COALESCE(Case When FinalApprovalDt is not null and mf.IncomingTocontrol = 1 and ContractPayoutAmt > 0
then DATEDIFF ( SECOND , ManualDecisionDt , lastChangesByAgentDt) End, 0)
+
COALESCE(Case When FinalApprovalDt is not null and mf.IncomingTocontrol = 0 and ContractPayoutAmt > 0
then DATEDIFF ( SECOND , SystemDecisionDt , lastChangesByAgentDt) End, 0)
) As Total_TTP,