嵌入式DATEDIFF排除周末+案例陈述

时间:2017-03-09 17:34:44

标签: sql-server-2008 datediff case-statement

我有以下使用case语句的查询。我想约会两个日期但不包括周末日。 我有以下的优惠,但现在我想排除星期六和星期日...和DATEDIFF(DD,A.ALERTS_CREATE_DT,S.CreatedDate)< = 2

CASE WHEN 
S.Name IN ('Assessment','Survey') 
  AND A.ALERT_DESC = 'ER'       
  AND CAST(A.ALERTS_CREATE_DT AS DATE) <= CAST(S.CreatedDate AS DATE) 
AND DATEDIFF(DD,A.ALERTS_CREATE_DT,S.CreatedDate) <= 2 /*EXCLUDE Sat and Sunday from the calculation*/   

完整查询

SELECT 

  CASE WHEN 
    S.Name IN ('Assessment','Survey') 
      AND A.ALERT_DESC = 'ER'       
      AND CAST(A.ALERTS_CREATE_DT AS DATE) <= CAST(S.CreatedDate AS DATE)
      AND  
      ( DATEDIFF(DD,A.ALERTS_CREATE_DT,S.CreatedDate) <= 2 /*Business Days*/   
      --DATEDIFF(DD,A.ALERTS_CREATE_DT,S.CreatedDate) + 1
      ---(DATEDIFF(WK,A.ALERTS_CREATE_DT,S.CreatedDate) * 2) 
      ---(CASE WHEN DATENAME(DW,A.ALERTS_CREATE_DT) = 'SUNDAY' THEN 1 ELSE 0 END)
      ---(CASE WHEN DATENAME(DW,S.CreatedDate) = 'SATURADAY' THEN 1 ELSE 0 END)
               )

   THEN 'Y'
    WHEN A.ALERT_DESC = 'model' OR S.CreatedDate IS NULL OR S.Name = 'ER'
    THEN ''
     ELSE 'N'
      END 'Count towards Alerts'

FROM A
FULL  S ON A.id= S.id

WHERE 1=1

1 个答案:

答案 0 :(得分:0)

这应该通过排除星期六和星期日给你所需的结果。

SELECT A.ALERT_DESC,A.ALERTS_CREATE_DT,S.Name,S.CreatedDate,
  CASE WHEN 
      S.Name IN ('Assessment','Survey')  AND A.ALERT_DESC = 'ER'       
      AND CAST(A.ALERTS_CREATE_DT AS DATE) <= CAST(S.CreatedDate AS DATE)
      AND  
        (( DATEDIFF(DD,A.ALERTS_CREATE_DT,S.CreatedDate)+1 
        - (datediff(wk,A.ALERTS_CREATE_DT,S.CreatedDate)*2) 
        - case when datepart(dw,A.ALERTS_CREATE_DT)=1 then 1 else 0 end 
        - case when datepart(dw,S.CreatedDate)=7 then 1 else 0 end
         )) <=2  THEN 'Y'
       WHEN A.ALERT_DESC = 'model' OR S.CreatedDate IS NULL OR S.Name = 'ER' THEN ''
       ELSE 'N' END 'Count towards Alerts'
FROM A,S