最大のPurchase_Cost
を持つ3人のユニーク顧客をどのようにクエリしますか?
DISTINCT
をCustomer_Name
にのみ適用したいのですが、以下のクエリは3つの列すべてに個別を適用します。クエリを変更して目的の出力を取得するにはどうすればよいですか?
SELECT DISTINCT TOP 3 customer_name, order_no, Purchase_Cost
FROM PurchaseTable
ORDER BY Purchase_Cost
次のクエリの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
同じことをする他の方法があると私は確信しています。 this を読むことをお勧めします。
してみてください:
SELECT DISTINCT TOP 3 order_no, customer_name, Purchase_Cost
FROM
( SELECT order_no, customer_name, Purchase_Cost, ROW_NUMBER() OVER(PARTITION BY customer_name ORDER BY Purchase_Cost DESC) Orders
FROM PurchaseTable
) A
WHERE A.Orders = 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
;