SELECT region, person, sum(dollars) as thousands
FROM sales
GROUP BY region, person
ORDER BY region, sum(dollars) desc
The SQL above produces a complete list of sales people per region like this
region person thousands
canada mike smith $114
canada joe blog $76
canada pete dodd $45
usa john doe $253
usa jane smyth $120
europe pieter tsu $546
europ mike lee $520
If I'm only interested in showing the top salesperson per region (as below), how can I best do that?
region person thousands
canada mike smith $114
usa john doe $253
europe pieter tsu $546
I've done something like burnall suggested. I wasn't getting much love with the "top 1 with ties" part, so I made the whole thing a subquery and chose rows where ranking = 1.
select *
from
(
select region,
person,
rank() over(partition by region order by sum(dollars) desc) as ranking
from sales
group by region,
person
) temp
where ranking = 1
Note that this also works for ties since rank() seems to place the same ranking on sums that are equal.