你可以在子查詢如下執行每個計數:
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;
我假設你有一個表叫賣場要做到這一點,並使用LEFT JOIN的上,並非每個店都有訪問或假設回顧。
我也使用了一種相當粗略的方法來計算一個客戶的平均年齡,但由於它只是一個平均值,並且實際上並沒有爲一個人計算出準確的年齡,我懷疑它會對結果產生不利影響
[你嘗試過什麼?](http://whathaveyoutried.com) – 2013-03-06 13:41:05