如何解决计算最近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
解决方法
您可以将查询调整为:
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;
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。