답변:
다음 쿼리에서 dbname 및 schemaName을 바꾸십시오.
;WITH CTE AS
(
SELECT
[Order_No]
,[Customer_Name]
,[Purchase_Cost]
, ROW_NUMBER() OVER(PARTITION BY [customer Name] ORDER BY [Purchase Cost] DESC) AS "RowNumber"
FROM [dbname].[schemaName].[PurchaseTable]
)
SELECT TOP(3)
[Order_No]
,[Customer_Name]
,[Purchase_Cost]
FROM CTE WHERE RowNumber=1
ORDER BY [Purchase_Cost] DESC
나는 같은 일을하는 다른 방법이 있다고 확신합니다. 나는 당신 이 이것을 읽는 것이 좋습니다 .
(Customer_Name, Purchase_Cost DESC) INCLUDE (Order_No)에 대한 색인이 있으면 다른 솔루션보다 더 효율적이라고 생각합니다.
;
WITH PurchaseTable AS
(
SELECT *
FROM (VALUES ((501),('Carson'),(3400)),
((502),('Thomas'),(625)),
((503),('Daisy'),(4856)),
((504),('Mary'),(2397)),
((505),('Carson'),(5000))
) AS T(Order_No,Customer_Name,Purchase_Cost)
),
DistinctCustomers AS
(
SELECT DISTINCT
Customer_Name
FROM PurchaseTable
)
SELECT TOP(3)
MaxCustomerOrder.Order_No,
dc.Customer_Name,
MaxCustomerOrder.Purchase_Cost
FROM DistinctCustomers dc
CROSS APPLY (SELECT TOP(1) *
FROM PurchaseTable pt
WHERE pt.Customer_Name = dc.Customer_Name
ORDER BY pt.Purchase_Cost DESC
) AS MaxCustomerOrder
ORDER BY MaxCustomerOrder.Purchase_Cost DESC
;
또는 인라인 테이블 정의가없는 경우 :
;
WITH DistinctCustomers AS
(
SELECT DISTINCT
Customer_Name
FROM PurchaseTable
)
SELECT TOP(3)
MaxCustomerOrder.Order_No,
dc.Customer_Name,
MaxCustomerOrder.Purchase_Cost
FROM DistinctCustomers dc
CROSS APPLY (SELECT TOP(1) *
FROM PurchaseTable pt
WHERE pt.Customer_Name = dc.Customer_Name
ORDER BY pt.Purchase_Cost DESC
) AS MaxCustomerOrder
ORDER BY MaxCustomerOrder.Purchase_Cost DESC
;