0

我正在使用 SQL Server 2008

我有一个这样的销售订单表

PartNo  Desc      OrderDate      OrderQty
60001   widget1   Apr-02-2012    3
60001   widget1   Apr-14-2012    5
60001   widget1   Jun-04-2012    3
60002   widget2   Jan-03-2012    1
60002   widget2   jan-17-2012    1
60002   widget2   aug-04-2012    30
60002   widget2   sep-02-2012    1
60003   widget3   oct-01-2012    4
60003   widget3   oct-04-2012    7
60003   widget3   oct-17-2012    3
60004   widget4   nov-04-2011    8
60004   widget4   nov-05-2011    8
60004   widget4   nov-05-2012    8
60004   widget4   nov-07-2012    7

我想返回一个表格,该表格是每个项目每月总数的最大值。它看起来像这样

PartNo    Desc     MaxSoldPerMonth  Month  Year
60001     widget1  8                Apr    2012
60002     widget2  30               Aug    2012
60003     widget3  14               oct    2012
60004     widget4  16               nov    2011

月份实际上是数字格式(即 nov = 11、oct = 10、apr = 4 等)我只是这样做以便于阅读。谢谢

4

2 回答 2

3

这应该这样做:

;WITH MonthlyOrders AS
(
    SELECT PartNo, [Desc], CONVERT(VARCHAR(6),OrderDate,112) YearMonth, SUM(OrderQty) OrderQty
    FROM YourTable
    GROUP BY PartNo, [Desc], CONVERT(VARCHAR(6),OrderDate,112)
),MaxOrders AS
(
    SELECT *, ROW_NUMBER() OVER(PARTITION BY PartNo, [Desc] ORDER BY OrderQty DESC) RN
    FROM MonthlyOrders
)
SELECT PartNo, [Desc], OrderQty MaxSoldPerMonth, YearMonth
FROM MaxOrders
WHERE RN = 1;
于 2012-11-19T19:59:59.843 回答
3

您可以使用以下内容:

;with cte as
(
  select partno, 
    [desc], 
    sum(orderqty) total,
    datename(month, orderdate) month, 
    year(orderdate) year,
    row_number() over(partition by partno order by sum(orderqty) desc) rn
  from yourtable
  group by partno, [desc],
    datename(month, orderdate), year(orderdate)
) 
select partno, [desc], total, month, year
from cte
where rn = 1

请参阅带有演示的 SQL Fiddle

于 2012-11-19T20:02:36.630 回答