I want to get each shops top salesperson, their total sales and the stores manager. If i query and get the max total sales and group by shop title, how do I also get the correct salesperson?
            Asked
            
        
        
            Active
            
        
            Viewed 48 times
        
    2 Answers
1
            
            
        You can use a correlated subquery:
select t.*
from t
where t.total_sales = (select max(t2.total_sales)
                       from t t2
                       where t2.shop_title = t.shop_title
                      );
 
    
    
        Gordon Linoff
        
- 1,242,037
- 58
- 646
- 786
- 
                    But this query doesn't show you the "other" top sales person name. – The Impaler Nov 27 '18 at 17:04
- 
                    @TheImpaler . . . I don't know what you mean. This returns the top sales record for each shop, which seems to be what the OP wants. – Gordon Linoff Nov 27 '18 at 20:58
1
            You could use inner join on subquery for max sales
select m.salesperson, t.max_sales, t.shop_title
from my_table m 
inner join (
    select max(sales) max_sales, shop_title
    from my_table
    group by shop_title
) t on t.shop_title = m.shop_title and t.max_sale = m.sales

 
     
    