您可以在子查询中执行每个计数,如下所示:
SELECT Stores.Store_ID,
review.AvgRating,
cv.VisitsLast20days,
cv.TotalVisits,
cv.AvgCustomerAge
FROM Stores
LEFT JOIN
( SELECT Store_ID, [AvgRating] = AVG(Rating)
FROM Reviews
GROUP BY Store_ID
) review
ON review.Store_ID = Stores.Store_ID
LEFT JOIN
( SELECT CustomerVisits.Store_ID,
[VisitsLast30Days] = COUNT(CASE WHEN CustomerVisits.VisitDate >= DATEADD(DAY, -30, CURRENT_TIMESTAMP) THEN 1 END),
[TotalVisits] = COUNT(*),
[AvgCustomerAge] = AVG(DATEDIFF(DAY, Customer.BirthDate, CURRENT_TIMESTAMP)) / 365.25
FROM CustomerVisits
INNER JOIN Customer
ON Customer.Customer_ID = CustomerVisits.Customer_ID
GROUP BY CustomerVisits.Store_ID
) cv
ON cv.Store_ID = Stores.Store_ID;
我假设您有一个名为 stores 的表来执行此操作,并在假设并非每个商店都有访问或评论的情况下使用 LEFT JOIN。
我还使用了一种相当粗略的方法来计算客户的平均年龄,但考虑到它只是一个平均值,实际上并没有计算出个人的准确年龄,我怀疑它会对结果产生不利影响