1

我正在尝试退回 2007 年每月订购最多的产品。我想查看产品的名称、当月订购的产品数量以及月份。我正在使用 AdventureWorks2012 数据库。我尝试了几种不同的方法,但每次都在同一个月退回多个产品订单,而不是当月订单数量最多的一种产品。对不起,如果这不清楚。我正在尝试测试自己,所以我自己提出问题并尝试回答它们。如果有人知道有这样的问题和答案的网站,那么我可以验证这将非常有帮助!谢谢你的帮助。这是我能够通过查询获得的最远距离。

WITH     Ord2007Sum
AS       (SELECT   sum(od.orderqty) AS sorder,
                   od.productid,
                   oh.orderdate,
                   od.SalesOrderID
          FROM     Sales.SalesOrderDetail AS od
                   INNER JOIN
                   sales.SalesOrderHeader AS oh
                   ON od.SalesOrderID = oh.SalesOrderID
          WHERE    year(oh.OrderDate) = 2007
          GROUP BY ProductID, oh.OrderDate, od.SalesOrderID)
SELECT   max(sorder),
         s.productid,
         month(h.orderdate) AS morder --, s.salesorderid
FROM     Ord2007Sum AS s
         INNER JOIN
         sales.SalesOrderheader AS h
         ON s.OrderDate = h.OrderDate
GROUP BY s.ProductID, month(h.orderdate)
ORDER BY morder;
4

2 回答 2

0

您的 group by 语句不应包含oh.OrderDate, od.SalesOrderID,因为这会将您的数据汇总到不正确的级别。您需要每月最常销售的 ProductID,以便按条件分组ProductID, datepart(mm,oh.OrderDate)。正如 Andrew 建议的那样,Row_Number 函数在这种情况下很有用,因为它允许您创建一个按月和 sorder 排序的键,并且每个月都会重置。最后在外部查询中将结果限制为每个月的第一个实例(这是最高数量)。

WITH     Ord2007Sum 
AS(
        SELECT  sum(od.orderqty) AS sorder,
                od.productid,
                datepart(mm,oh.OrderDate) AS 'Month'
                row_number() over (partition by datepart(mm,oh.OrderDate)
                                    Order by datepart(mm,oh.OrderDate)desc, sorder desc) row
        FROM    Sales.SalesOrderDetail AS od
                INNER JOIN
                sales.SalesOrderHeader AS oh
             ON od.SalesOrderID = oh.SalesOrderID
        WHERE    datepart(yyyy,oh.OrderDate) = 2007
        GROUP BY ProductID, datepart(mm,oh.OrderDate)
    )

SELECT  productid,
        sorder,
        [month]
FROM    Ord2007Sum 
WHERE   row =1  
于 2014-07-28T20:37:00.420 回答
0

制作按月对我们的产品进行分组并创建总和的 CTE

;WITH OrderRows AS
(
    SELECT
        od.ProductId, 
        MONTH(oh.OrderDate) SalesMonth,
        SUM(od.orderqty) OVER (PARTITION BY od.ProductId, MONTH(oh.OrderDate) ORDER BY oh.OrderDate) ProdMonthSum
    FROM SalesOrderDetail AS od
    INNER JOIN SalesOrderHeader AS oh
        ON od.SalesOrderID = oh.SalesOrderID
    WHERE year(oh.OrderDate) = 2007
),

制作一个简单的数字表来分解一年中的每个月

Months AS
(
    SELECT 1 AS MonthNum UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 
    UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 
    UNION SELECT 9 UNION SELECT 10 UNION SELECT 11 UNION SELECT 12
)

我们根据数据查询我们的月份表,并根据总和选择每个月的顶级产品

SELECT 
    m.MonthNum,
    d.ProductID,
    d.ProdMonthSum
FROM Months m
OUTER APPLY
(
    SELECT TOP 1 r.ProductID, r.ProdMonthSum 
    FROM OrderRows r
    WHERE r.SalesMonth = m.MonthNum
    ORDER BY ProdMonthSum DESC
) d
于 2014-07-28T20:33:58.000 回答