I am trying to write a SQL query that will return the top items for each company and for each location. I have an example MySQL table (table_x) that looks like this:
Date | Company | Location | Item | Price | Quantity | Total_Amount
----------|---------|----------|--------------|-------|----------|-------------
1/10/2000 | ABC | 1 | Food | 2 | 6 | 12
1/11/2000 | ABC | 1 | Food | 1 | 2 | 2
1/12/2000 | ABC | 2 | Food | 10 | 5 | 50
1/13/2000 | ABC | 2 | Electronics | 100 | 2 | 200
1/10/2000 | ABC | 1 | Consumables | 10 | 5 | 50
1/15/2000 | ABC | 2 | Electronics | 100 | 3 | 300
1/10/2000 | DEF | 1 | Electronics | 50 | 5 | 250
1/16/2000 | DEF | 1 | Electronics | 50 | 4 | 200
1/19/2000 | DEF | 2 | Food | 10 | 5 | 50
1/14/2000 | DEF | 2 | Food | 2 | 10 | 20
1/11/2000 | DEF | 2 | Food | 5 | 8 | 40
1/11/2000 | DEF | 2 | Electronics | 500 | 2 | 1000
And for example what I want is to return is the top item by count per company per location. So something like this where the top item by count is per company and per location.
Company | Location | Item | AVG(Price) | SUM(Total_Amount) | COUNT(*)
--------|----------|-------------|------------|-------------------|---------
ABC | 1 | Food | 4 | 14 | 2
ABC | 2 | Electronics | 100 | 500 | 2
DEF | 1 | Electronics | 50 | 450 | 2
DEF | 2 | Food | 5.67 | 110 | 3
I know how to do this across all company and locations, but have trouble getting the top items by count to be within each specific grouping. Ideally, I'd want to be able to extend this to top N items if I have more item types if possible.
This is the SQL query I ran to generate top items based on the occurrences.
SELECT Company, Location, Item, AVG(Price), SUM(Total_Amount), COUNT(*) FROM table_x
GROUP BY Company, Location, Item
ORDER BY Company, Location, COUNT(*) desc