SQL Query with Group By语句

时间:2016-09-10 09:37:30

标签: sql sql-server

我有这4张桌子:

经理,销售,销售详情,产品:

  • 经理:ID,姓名
  • 销售:ID,ManagerID,SaleNO,SaleDate
  • SaleDetails :ID,SaleID,ProductID,数量
  • 产品:ID,名称,价格

我想为每位经理进行审核: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

这是最佳的吗?你能帮助我用更优化的查询替换它吗

  • 经理:[ID = 1,姓名=约翰;]
  • 销售:[ID = 1,ManagerID = 1,SaleNO = 0015,SaleDate:2016-09-08],[ID = 2,ManagerID = 1,SaleNO = 0016,SaleDate:2016-09-09]
  • SaleDetails:[ID = 1,SaleID = 1,ProductID = 1,Quantity = 2],[ID = 2,SaleID = 1,ProductID = 1,Quantity = 4],[ID = 3,SaleID = 1, ProductID = 2,Quantity = 3],[ID = 4,SaleID = 2, ProductID = 1,Quantity = 3]
  • 产品:[ID = 1,名称=索尼],[ID = 2,名称=三星]

查询必须返回结果:

  • ManagerName = John,SaleDate = 2016-09-08,ProductCount = 2
  • ManagerName = John,SaleDate = 2016-09-09,ProductCount = 1

2 个答案:

答案 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表包含产品信息。
  • 产品ID不在GROUP BY
  • 正确的聚合函数是COUNT(DISTINCT)