Adventureworks2008R2数据库 我想要的结果是每天出售的MaxQantity,例如,OrderDate 2007-09-01的最大数量应为96,但是我的查询给我当天的3个不同结果,可能是因为它考虑了时间戳为好
SELECT DISTINCT CAST(oh.OrderDate AS DATE) OrderDate, (od.ProductID),SUM(od.OrderQty) MAXOrderQty
FROM Sales.SalesOrderDetail od
Inner Join Sales.SalesOrderHeader oh
ON od.SalesOrderID = oh.SalesOrderID
GROUP BY od.ProductID, CAST(oh.OrderDate AS DATE), od.OrderQty
ORDER BY SUM(od.OrderQty) DESC
答案 0 :(得分:1)
您可以通过CTE
以JOIN
的数量写MAX
和自己date
;WITH CTE(OrderDate,ProductID,MAXOrderQty) AS(
SELECT CAST(oh.OrderDate AS DATE) OrderDate,od.ProductID,SUM(od.OrderQty) MAXOrderQty
FROM Sales.SalesOrderDetail od
Inner Join Sales.SalesOrderHeader oh
ON od.SalesOrderID = oh.SalesOrderID
GROUP BY od.ProductID, CAST(oh.OrderDate AS DATE)
)
SELECT t1.*
FROM CTE t1 INNER JOIN (
select OrderDate,MAX(MAXOrderQty) 'MAXOrderQty'
from CTE
GROUP BY OrderDate
)t2 on t1.OrderDate = t2.OrderDate and t1.MAXOrderQty = t2.MAXOrderQty
答案 1 :(得分:0)
使用窗口函数解决此类问题要容易得多。在这种情况下,rank
应该可以解决问题:
SELECT OrderDate, ProductID, MaxOrderQty
FROM (SELECT OrderDate, ProductID, MaxOrderQty,
RANK() OVER (PARTITION BY OrderDate ORDER BY MaxOrderQty DESC) AS rk
FROM Sales.SalesOrderDetail) s
WHERE rk = 1