简体   繁体   中英

Select row that has max total value SQL Server

I have the following scheme (2 tables):

Customer (Id, Name) and Sale (Id, CustomerId, Date, Sum)

How to select the following data ?

1) Best customer of all time (Customer, which has Max Total value in the Sum column)

For example, I have 2 tables (Customers and Sales respectively):

id    CustomerName      
---|--------------
1  | First         
2  | Second 
3  | Third 



id  CustomerId  datetime     Sum
---|----------|------------|-----
1  | 1        | 04/06/2013 | 50
2  | 2        | 04/06/2013 | 60
3  | 3        | 04/07/2013 | 30
4  | 1        | 03/07/2013 | 50
5  | 1        | 03/08/2013 | 50
6  | 2        | 03/08/2013 | 30
7  | 3        | 24/09/2013 | 20

Desired result:

CustomerName TotalSum
------------|--------
 First      | 150

2) Best customer of each month in the current year (the same as previous but for each month in the current year)

Thanks.

Try this for the best customer of all times

SELECT Top 1 WITH TIES c.CustomerName, SUM(s.SUM) AS TotalSum
FROM Customer c JOIN Sales s ON s.CustomerId = c.CustomerId
GROUP BY c.CustomerId, c.CustomerName
ORDER BY SUM(s.SUM) DESC

One option is to use RANK() combined with the SUM aggregate. This will get you the overall values.

select customername,  sumtotal
from (
  select c.customername, 
    sum(s.sum) sumtotal,
    rank() over (order by sum(s.sum) desc) rnk
  from customer c
    join sales s on c.id = s.customerid
  group by c.id, c.customername
  ) t
where rnk = 1

Grouping this by month and year should be trivial at that point.

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