在一列上区分并返回TOP行


9

您如何查询三个最大的唯一客户Purchase_Cost

我想在上应用DISTINCT唯一Customer_Name,但是下面的查询在所有三列上应用了非重复。我应该如何修改查询以获得所需的输出?

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

在此处输入图片说明

Answers:


9

在以下查询中替换您的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

我相信还有其他方法可以做到这一点。我建议你读这篇


1

请试试:

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

0

我认为,如果您有以下指标的索引,这可能会比其他解决方案更有效:(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
;

第一个查询看起来无效。
dezso

我试图解决它。不知道查询1和2之间有什么区别。
ypercubeᵀᴹ17年

查询2只是删除了内联表数据。如果实际上有包含数据的表,则不需要它。如果没有像我这样的实际表,则需要它来测试它是否运行。
乔纳森·罗伯茨
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.