WHERE子句中的Datediff不起作用

时间:2015-11-10 19:25:20

标签: sql sql-server-2012

我有以下脚本。我需要在30天内获得客户回来的所有访问。脚本中的一切工作正常但where子句中的datediff。有人可以帮我修一下逻辑吗?

select OverallNumber,VisitID,coalesce(CheckInDateTime,ServiceDateTime) as ArrivalDateTime, DepartDateTime
from Visits 
where OverallNumber='100'
and DepartDateTime is not null
and coalesce(CheckInDateTime,ServiceDateTime) is not null
--and DATEDIFF(day,MIN(coalesce(CheckInDateTime,ServiceDateTime)), Max(DepartDateTime))<30
order by ArrivalDateTime;

当前数据:

OverallNumber   VisitID ArrivalDateTime DepartDateTime
100              1      6/13/2015       6/15/2015
100              2      11/5/2015       11/7/2015
100              3      11/20/2015      11/25/2015

Desired:
OverallNumber   VisitID ArrivalDateTime DepartDateTime
    100              2      11/5/2015       11/7/2015
    100              3      11/20/2015      11/25/2015

在此示例中,客户从2015年11月5日到2015年11月25日两次回来。请帮忙。感谢。

1 个答案:

答案 0 :(得分:1)

SELECT OverallNumber,
        VisitID,
        ArrivalDateTime,
        DepartDateTime
FROM (
    SELECT
        OverallNumber,
        VisitID,
        ArrivalDateTime,
        DepartDateTime,
        LAG(DepartDateTime, 1, NULL) OVER (PARTITION BY OverallNumber ORDER BY ArrivalDateTime) PreviousDateDiff,
        LEAD(ArrivalDateTime, 1, NULL) OVER (PARTITION BY OverallNumber ORDER BY ArrivalDateTime) NextDateDiff
    FROM (
        SELECT  
            *, 
            COALESCE(CheckInDateTime,ServiceDateTime) ArrivalDateTime 
        FROM    
            Visits
        WHERE
            OverallNumber = '100'
            AND DepartDateTime IS NOT NULL) t         
    ) v
WHERE 
    ArrivalDateTime < DATEADD(day, 30, PreviousDateDiff)
    OR DATEADD(day, -30, NextDateDiff) < DepartDateTime
ORDER BY
    ArrivalDateTime;

延迟会为您提供之前的DepartDateTime,并且潜在客户功能会为您提供下一个ArrivalDateTime