SQL Server-SELECT语句未返回结果

时间:2018-10-15 18:50:05

标签: sql sql-server adventureworks

使用AdventureWorks数据库,我被问到“ 列出订单客户名称,订单状态,订购日期,订单项数以及所订购的平均项数”大于300 ”。但是,我下面的SELECT语句不返回任何结果...我在做什么错了?

SELECT scpii.LastName + ', ' + scpii.FirstName AS 'Customer Name', ssoh.Status AS 'Order Status', ssoh.OrderDate AS 'Date Ordered', SUM (ssod.OrderQty) AS 'Count of Items', AVG (ssod.OrderQty) AS 'Average Quantity'
FROM Sales.CustomerPII scpii
INNER JOIN Sales.SalesOrderHeader ssoh
ON ssoh.CustomerID = scpii.CustomerID
INNER JOIN Sales.SalesOrderDetail ssod
ON ssod.SalesOrderID = ssoh.SalesOrderID
GROUP BY scpii.LastName, scpii.FirstName, ssoh.Status, ssoh.OrderDate, ssod.OrderQty
HAVING SUM(ssod.OrderQty) > 300;

1 个答案:

答案 0 :(得分:5)

  • 您不需要在ProductIDOrderqty上进行分组依据。如果对它们进行分组,则将其分组到单个订单项级别。因此,您将永远无法计数超过300
  • 已订购的商品数实际上应该是Orderqty的总和。

尝试:

SELECT scpii.LastName + ', ' + scpii.FirstName AS 'Customer Name', 
       ssoh.Status AS 'Order Status', 
       ssoh.OrderDate AS 'Date Ordered', 
       SUM (ssod.OrderQty) AS 'Count of Items', 
       AVG (ssod.OrderQty) AS 'Average Quantity'
FROM Sales.CustomerPII scpii
INNER JOIN Sales.SalesOrderHeader ssoh
  ON ssoh.CustomerID = scpii.CustomerID
INNER JOIN Sales.SalesOrderDetail ssod
  ON ssod.SalesOrderID = ssoh.SalesOrderID
GROUP BY scpii.LastName, 
         scpii.FirstName, 
         ssoh.Status, 
         ssoh.OrderDate 
HAVING SUM (ssod.OrderQty) > 300;