我有这4张桌子:
经理,销售,销售详情,产品:
我想为每位经理进行审核:SaleDate和唯一的产品数量;
我的选择如下:
;WITH cte
AS
(
SELECT sd.SaleID, sd.ProductID FROM dbo.Products p
INNER JOIN dbo.SalesDetails sd ON sd.ProductID = p.ID
GROUP BY sd.SaleID, sd.ProductID
)
SELECT
c.Name AS ManagerName
,s.SaleDate
,COUNT(ct.ProductID) AS ProductCount
FROM cte ct
INNER JOIN dbo.Sales s ON ct.SaleID = s.ID
INNER JOIN dbo.Managers c ON c.ID = s.ConsultantID
GROUP BY s.SaleDate, c.Name
这是最佳的吗?你能帮助我用更优化的查询替换它吗
查询必须返回结果:
答案 0 :(得分:2)
SELECT c.Name AS ManagerName
,s.SaleDate
,COUNT(p.ProductID)
FROM dbo.Products p
INNER JOIN dbo.SalesDetails sd ON sd.ProductID = p.ID
INNER JOIN dbo.Sales s ON sd.SaleID = s.ID
INNER JOIN dbo.Managers c ON c.ID = s.ConsultantID
GROUP BY s.SaleDate, c.Name,sd.ProductID
答案 1 :(得分:1)
正确答案(正如我读到的问题)是:
SELECT c.Name AS ManagerName, s.SaleDate, COUNT(DISTINCT sd.ProductId)
FROM dbo.SalesDetails sd
dbo.Sales s
ON sd.SaleID = s.ID INNER JOIN
dbo.Managers c
ON c.ID = s.ConsultantID
GROUP BY s.SaleDate, c.Name;
注意:
Products
表,因为SalesDetails
表包含产品信息。GROUP BY
。COUNT(DISTINCT)
。