计算最近7天在SQL中发生的情况

问题描述

我有一个带有CustomerID和ArrivalDateTime(日期时间)的表。我想计算在每个到达日期的最后7天内CutomerID的出现。

我想出了以下sql语句,但是它不起作用。

有人可以帮我做错什么吗?
谢谢

SELECT d1.DateValue,cr1.CustomerID,COUNT(ISNULL(cr2.CustomerID,0)) as [No_of_presentation]
FROM [dbo].[CustomerPresentation] cr1 join DimDate d1 on d1.DateValue = cr1.Arrivaldate
    Left JOIN [dbo].[CustomerPresentation] cr2 ON cr1.CustomerID = cr2.CustomerID
    join DimDate d2 on d2.DateValue= cr2.ArrivalDate
WHERE (d1.DateValue BETWEEN DATEADD(dd,-7,d2.DateValue) AND d2.DateValue)
GROUP BY d1.DateValue,cr1.CustomerID

Result of the above query and expected result

解决方法

您可以将查询调整为:

SELECT d1.DateValue,cr1.CustomerID,COUNT(*) as No_of_presentation
FROM dbo.CustomerPresentation cr1 JOIN
     DimDate d1 
     ON d1.DateValue = cr1.Arrivaldate JOIN
     dbo.CustomerPresentation cr2
     ON cr1.CustomerID = cr2.CustomerID JOIN
     DimDate d2 
     ON d2.DateValue= cr2.ArrivalDate
WHERE d2.DateValue >= DATEADD(day,-7,d1.DateValue) AND 
      d2.DateValue <= d1.DateValue
GROUP BY d1.DateValue,cr1.CustomerID;

请注意,LEFT JOIN不是必需的。每行将自己匹配。我认为您查询中的问题是日期向后。

也就是说,我建议使用相关子查询或apply编写查询。我也不认为加入日期维度是必要的。您正在使用的密钥似乎是日期。所以:

select cr.*,cd.cnt_7
from dbo.CustomerPresentation cr cross apply
     (select count(*) as cnt_7
      from  dbo.CustomerPresentation cr2
      where cr2.CustomerID = cr.CustomerID and
            cr2.ArrivalDate >= dateadd(day,cr.ArrivalDate) and
            cr2.ArrivalDate <= cr.ArrivalDate
     ) cd;