获取所需信息的实际查询本身非常简单:
-- NOTE: if you want to exclude product records for which there
-- are no sales, use an INNER JOIN instead
SELECT p.ProductID, p.StartDate, p.EndDate, COUNT(*) [NumSales]
FROM Products p
LEFT JOIN Sales s
ON s.ProductID = p.ProductID
WHERE s.SaleDate BETWEEN p.StartDate AND p.EndDate
GROUP BY p.ProductID, p.StartDate, p.EndDate
但是,我建议不要根据这些信息制作单独的表格,因为它需要不断更新。相反,如果这是一个您认为会经常运行的查询,那么我建议将其转换为VIEW
:
CREATE VIEW CountSalesView AS
SELECT p.ProductID, p.StartDate, p.EndDate, COUNT(*) [NumSales]
FROM Products p
LEFT JOIN Sales s
ON s.ProductID = p.ProductID
WHERE s.SaleDate BETWEEN p.StartDate AND p.EndDate
GROUP BY p.ProductID, p.StartDate, p.EndDate
从那里,您可以在需要最新信息的任何时候像查询表格一样查询它:
SELECT *
FROM CountSalesView
以下是一些实际的例子: