I have an ecommerce table 'orders', and the table has a 'state' record and a 'fruit' record. I am trying (and failing) to create a query that will return a result of every state and the top 3 most popular fruits, shown in order.
So the 'orders' table looks like this:
id State Fruit
----------------
1 CA grape
2 FL orange
3 CA grape
4 FL grapefruit
5 CA orange
6 CA grape
7 FL orange
8 CA peach
9 CA orange
10 FL orange
11 FL grapefruit
12 FL peach
etc etc etc
The result of the query on this table would be:
the_state the_fruits
------------------------
CA grape, orange, peach
FL orange, grapefruit, peach
I tried this:
SELECT state as the_state,
(select count(id) as count, fruit from orders where state = the_state order by count(id) limit 3 ) as the_fruits
FROM orders
group by fruit
order by count(id) DESC
But that is not valid a valid query, and I am not sure I am on the right track