が必要だと思います。それはもっと多くの詳細がありますが、それはAdventureWorksで実行するように設計されているためです(どのバージョンをどのように使用するかわからないため)。
USE AdventureWorks
;WITH OrderDetails
AS (
SELECT soh.SalesOrderID, CAST(soh.OrderDate AS DATE) AS OrderDate,
SUM(sod.OrderQty * (sod.UnitPrice - pch.StandardCost)) AS OrderMargin
FROM Sales.SalesOrderHeader soh
LEFT JOIN Sales.SalesOrderDetail sod
ON soh.SalesOrderID = sod.SalesOrderID
LEFT JOIN Production.ProductCostHistory pch
ON sod.ProductID = pch.ProductID
WHERE soh.OrderDate >= pch.StartDate AND soh.OrderDate <= pch.EndDate
GROUP BY soh.SalesOrderID, soh.OrderDate
),
MaxOrder
AS (
SELECT DATEPART(yy,OrderDate) AS Year, DATEPART(ww,OrderDate) AS Week,
MAX(OrderMargin) AS MaxOrderMargin
FROM OrderDetails
GROUP BY DATEPART(yy,OrderDate), DATEPART(ww,OrderDate)
)
SELECT mo.Year, mo.Week, od.SalesOrderID, '$'+FORMAT(mo.MaxOrderMargin,'#,0.00') AS OrderMargin
FROM MaxOrder mo
INNER JOIN OrderDetails od
ON mo.MaxOrderMargin = od.OrderMargin
WHERE DATEPART(yy,od.OrderDate) = mo.Year AND DATEPART(ww,od.OrderDate) = mo.Week
ORDER BY Year, Week
これは少しだけある点で、前の例以上の機能を向上させた、そしてそれは余裕をもってすべての注文が含まれますので、それが複数ある場合でも、です。ただし、これはROW_NUMBER()の代わりにRANK()を使用して実現できることに注意してください。 CTEを使用してここに表示する:
USE AdventureWorks
;WITH OrderDetails
AS (
SELECT soh.SalesOrderID, CAST(soh.OrderDate AS DATE) AS OrderDate,
SUM(sod.OrderQty * (sod.UnitPrice - pch.StandardCost)) AS OrderMargin
FROM Sales.SalesOrderHeader soh
LEFT JOIN Sales.SalesOrderDetail sod
ON soh.SalesOrderID = sod.SalesOrderID
LEFT JOIN Production.ProductCostHistory pch
ON sod.ProductID = pch.ProductID
WHERE soh.OrderDate >= pch.StartDate AND soh.OrderDate <= pch.EndDate
GROUP BY soh.SalesOrderID, soh.OrderDate
),
OrderRank
AS (
SELECT DATEPART(yy,OrderDate) AS Year, DATEPART(ww,OrderDate) AS Week,
SalesOrderID, '$'+FORMAT(OrderMargin,'#,0.00') AS OrderMargin,
RANK() OVER (PARTITION BY DATEPART(yy,OrderDate), DATEPART(ww,OrderDate) ORDER BY OrderMargin DESC) AS MRank
FROM OrderDetails
),
MRank
AS (
SELECT Year, Week, SalesOrderID, OrderMargin
FROM OrderRank
WHERE MRank = 1
)
SELECT * FROM MRank