[英]Calculate occurrences in the last 7 days in 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
您可以将查询调整为:
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, -7, cr.ArrivalDate) and
cr2.ArrivalDate <= cr.ArrivalDate
) cd;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.