I have a table that includes names, items, types, and a count per item. I need to find a way to determine the name that has the MAX count in each type.
Example table:
---------------------------------------
| name | item | type | count |
| ------------------------------------|
| Dave | carrot | vegetable | 2 |
| Dave | broccoli | vegetable | 3 |
| Tom | spinach | vegetable | 2 |
| Jon | swiss | cheese | 3 |
| Mark | cheddar | cheese | 5 |
| Jon | cheddar | cheese | 6 |
| Tony | onion | vegetable | 3 |
I want to find the names of each person with the highest SUM(count) in each type. This is my expected result:
----------------------------
| name | type | count |
| -------------------------|
| Dave | vegetable | 5 |
| Jon | cheese | 9 |
I’m trying to see if there is an elegant way of doing it other than queries for every name and then manually calculating the MAX.
First calculate the totals for each name/category combination. Do this either in a subquery or a view. I’m going to choose a view to reduce code bloat, since it will be needed more than once.
Now you need to find the maximum count for each type.
Now you just need to query the view
totalsfor all rows where (type, count) is equal to any of the pairs in the second result set. I’ve already done most of the work for you. I’ll leave you to finish it off.