I have these 3 tables with the following structures:
Products
product_id | category_id | product_name
Customers
customer_id | customer_name
Orders
order_id | customer_id | product_id
I need to write a SQL query that will print the top customers regarding the number of categories they have bought products from (the best customer is the one that has bought from the most categories).
Can anyone show me how to do that?
I tried like this, but I get the following error "not a GROUP BY expression":
select 
    (select customer_name 
     from customers 
     where customers.customer_id = orders.customer_id) as name,    
    (select count(category_id) 
     from products 
     where products.product_id = orders.product_id)
from 
    orders
group by 
    customer_id
order by 
    count(customer_id) desc;
I managed to make the top regarding how many products the customers bought. The solution I used is:
select 
    (select customer_name from customers 
     where customers.customer_id = orders.customer_id) as name,   
    count(product_id) as "number of ordered products"
from 
    orders
group by 
    customer_id
order by 
    count(product_id) desc;
 
     
    