简体   繁体   中英

SQL Server how to get the top sales row from a group of rows

I am working on a query in SQL Server 2012 but I am stuck. Basically I need to get the top 1 sales row from a group of rows ordered by Country and Product Name. The 3 columns are from 3 different tables:

Customers, Product, Orders

After running this query:

SELECT    
    c.Country, p.ProductName AS [Product Name], 
    SUM(o.TotalPrice) AS [Sales Revenue]
FROM      
    Orders o 
JOIN      
    Customers c ON o.CustomerID = c.CustomerID
JOIN      
    Products p ON o.ProductID = p.ProductID
GROUP BY  
    c.Country, p.ProductName
ORDER BY  
    c.Country, SUM(o.TotalPrice) DESC

I get the following result:

Country      Product Name      Sales Revenue 
---------------------------------------------
Argentina    Marmalade         2620.00   
Argentina    Queso Cabrales    630.00    
Austria      Spegesild         432.00    
Belgium      Courdavault       4950.00   
Belgium      Ipoh Coffee       2557.60   
Belgium      Flotemysost       1505.00   
Belgium      Alice Mutton      1248.00   

I need the result to be shown exactly like the table format above:

Country      Product Name      Sales Revenue
---------------------------------------------
Argentina    Marmalade         2620.00  
Austria      Spegesild         432.00    
Belgium      Courdavault       4950.00   

Tried to use max on sum() but it didn't work. Also tried TOP 1 but couldn't figure it out. Please help. Thanks!

You could use a Common Table Expression(CTE) to partition the data by country and in descending order by SUM(o.TotalPrice).

WITH records
AS
(
  SELECT c.Country,
         p.ProductName     AS [Product Name],
         SUM(o.TotalPrice) AS [Sales Revenue],
         ROW_NUMBER() OVER (PARTITION BY c.Country
                                ORDER BY SUM(o.TotalPrice) DESC) RN          
    FROM Orders o 
    JOIN Customers c ON o.CustomerID = c.CustomerID
    JOIN Products  p ON o.ProductID = p.ProductID
GROUP BY c.Country, p.ProductName
)
 SELECT Country,
        [Product Name],
        [Sales Revenue]
  FROM  records
 WHERE RN = 1 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM