Quantcast
Channel: DISTINCT on one column and return TOP rows - Database Administrators Stack Exchange
Viewing all articles
Browse latest Browse all 4

Answer by Jonathan Roberts for DISTINCT on one column and return TOP rows

$
0
0

I think this could be more efficient that the other solutions, provided you have an index on: (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;

Or without the inline table definition:

;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;

Viewing all articles
Browse latest Browse all 4

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>