-2

I am trying to get the highest spend and show the vendor that has the highest spend in the category . Here is what i have:

Vendor    Category   Spend
3M         cat1       200
XX         cat6       150
Bos        cat1       700
JJ         cat0       500
KLM        cat0       100       
XX         cat0       400

This is the desired results:

Vendor    Category   Spend
XX         cat6       150
Bos        cat1       700
JJ         cat0       500

i am not getting the right results

select vendor, category, sum(spend) ,row_number() over(partition by vendor order by spend desc) as roworder
from myTable
group by vendor, category
1
  • This has been asked so many times. Gordon has a literally identical answer on one of those that has been highlighted as a duplicate. Commented Oct 23, 2019 at 17:29

1 Answer 1

1

Use a correlated subquery to filter the data:

select t.*
from myTable t
where t.spend = (select max(t2.spend)
                 from myTable t2
                 where t2.category = t.category
                );

You can also use window functions:

select t.*
from (select t.*,
             row_number() over (partition by category order by spend desc) as seqnum
      from myTable t
     ) t
where seqnum = 1;

Use rank() if you want ties in the event of duplicate max values.

Sign up to request clarification or add additional context in comments.

4 Comments

Gordon, i need to sum the spend because sometimes there are multiple vendor and categories with the same vendor names and categories but different spend so i need to always sum the spend
You don't "SUM" spend in your expected results, @moe . The value is 700 for cat1 for example, not 900.
this was just a sample data but in my real data i have where vendor and category are the same but with different spend. sorry i was trying simplify the sample data
If your sample data isn't representative of the problem @moe then you aren't going to get representative answers. I suggest posting a new question (possibly deleting this one) with a more informative sample set and results.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.