9

How do you query for three unique customers with the largest Purchase_Cost?

I want to apply the DISTINCT only on Customer_Name, but the query below applies the distinct on all three columns. How should I modify the query to obtain the desired output?

SELECT DISTINCT TOP 3 customer_name, order_no, Purchase_Cost  
FROM PurchaseTable 
ORDER BY Purchase_Cost

enter image description here

Paul White
  • 94,921
  • 30
  • 437
  • 687
Neal
  • 93
  • 1
  • 1
  • 3

3 Answers3

9

Replace your dbname and schemaName in the following query.

;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

I am sure there are other ways of doing the same. I suggest you read this.

paparazzo
  • 5,048
  • 1
  • 19
  • 32
SqlWorldWide
  • 13,687
  • 3
  • 30
  • 54
1

please try:

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
Fatih
  • 11
  • 2
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
;
ypercubeᵀᴹ
  • 99,450
  • 13
  • 217
  • 306