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.
jointhe tables first. Then you can Sum or aggregate the individual Sum and find the Max Value. Please take some steps to show us the effort you have already taken. Great description of the problem though.SELECT Customer.Name, TotalSum FROM Customer INNER JOIN (SELECT Sale.CustomerId, SUM(Sum) as TotalSum FROM Sale GROUP BY Sale.CustomerId )temp ON Customer.Id = temp.CustomerIdI got the result-set with two columns (CustomerName, TotalSum) and three rows (for each Customer). But how at this point to select Customer with Max TotalSum?