For each name, I need to output the category with the MAX net revenue and I am not sure how to do this. I have tried a bunch of different approaches, but it basically looks like this:
SELECT Name, Category, MAX(CatNetRev)
FROM (
SELECT Name, Category, SUM(Price*(Shipped-Returned)) AS "CatNetRev"
FROM a WITH (NOLOCK)
    INNER JOIN b WITH (NOLOCK) ON b.ID = a.ID
    ...
    -- (bunch of additional joins here, not relevant to question)
WHERE ... -- (not relevant to question)
GROUP BY Name, Category
) a GROUP BY Name;
This currently doesn't work because "Category" is not contained in an aggregate function or Group By (and this is obvious) but other approaches I have tried have failed for different reasons.
Each Name can have a bunch of different Categories, and Names can have the same Categories but the overlap is irrelevant to the question. I need to output just each unique Name that I have (we can assume they are already all unique) along with the "Top Selling Category" based on that Net Revenue calculation.
So for example if I have:
| Name: | Category: | "CatNetRev": | 
|---|---|---|
| A | 1 | 100 | 
| A | 2 | 300 | 
| A | 3 | 50 | 
| B | 1 | 300 | 
| B | 2 | 500 | 
| C | 1 | 40 | 
| C | 2 | 20 | 
| C | 3 | 10 | 
I would want to output:
| Name: | Category: | 
|---|---|
| A | 2 | 
| B | 2 | 
| C | 1 | 
What's the best way to go about doing this?
 
     
     
    