查找每天最畅销产品的产品ID,使用总销售量确定最畅销产品

时间:2018-06-23 21:04:09

标签: sql-server adventureworks

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 

Screenshot of my output

2 个答案:

答案 0 :(得分:1)

您可以通过CTEJOIN的数量写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