我对当前联接有问题。出于某些原因,聚合函数返回的金额不正确。当我运行以下查询时,结果中没有任何行:
SELECT
CONCAT( pp.FirstName, ' ', pp.LastName) AS 'CustomerName',
ssoh.Status AS 'OrderStatus',
FORMAT (ssoh.OrderDate, 'yyyy-dd-MM') AS OrderDate, ItemCount, AvgQty
FROM Sales.SalesOrderHeader AS ssoh
JOIN Person.Person AS pp ON pp.BusinessEntityID = ssoh.CustomerID
JOIN (
SELECT SalesOrderID, SUM(ssod.OrderQty) AS ItemCount, AVG(ssod.OrderQty) AS AvgQty
FROM Sales.SalesOrderDetail AS ssod
GROUP BY ssod.SalesOrderID
HAVING SUM(ssod.OrderQty) > 300
) AS ssod ON ssoh.SalesOrderID = ssod.SalesOrderID
ORDER BY ssod.ItemCount DESC
当我分别运行此查询时:
Select SUM(OrderQty), SalesOrderID
From Sales.SalesOrderDetail
Where SUM(OrderQty) > 300
Group BY SalesOrderID
Order by desc
go
我得到一些行,这意味着我的思维方式没有错,并且我在脚本中犯了一个错误。请帮帮我。
答案 0 :(得分:0)
您需要使用不在此处的位置:
Select SUM(OrderQty) as s, SalesOrderID
From Sales.SalesOrderDetail
Group BY SalesOrderID
HAVING SUM(OrderQty) > 300
Order by s desc
编辑以获取在SQL Server上工作的命令
SELECT x.s, x.salesorderid
FROM (
Select SUM(OrderQty) as s, SalesOrderID
From Sales.SalesOrderDetail
Group BY SalesOrderID
HAVING SUM(OrderQty) > 300
) x
Order by x.s desc