Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using SQL query to find details of customers who ordered > x types of products

Please note that I have seen a similar query here, but think my query is different enough to merit a separate question.

Suppose that there is a database with the following tables:

  1. customer_table with customer_ID (key field), customer_name
  2. orders_table with order_ID (key field), customer_ID, product_ID

Now suppose I would like to find the names of all the customers who have ordered more than 10 different types of product, and the number of types of products they ordered. Multiple orders of the same product does not count.

I think the query below should work, but have the following questions:

  1. Is the use of count(distinct xxx) generally allowed with a "group by" statement?
  2. Is the method I use the standard way? Does anybody have any better ideas (e.g. without involving temporary tables)?

Below is my query

select T1.customer_name, T1.customer_ID, T2.number_of_products_ordered
from customer_table T1
inner join 
(
    select cust.customer_ID as customer_identity, count(distinct ord.product_ID) as number_of_products_ordered
    from customer_table cust
    inner join order_table ord on cust.customer_ID=ord.customer_ID
    group by ord.customer_ID, ord.product_ID
    having count(distinct ord.product_ID) > 10
) T2
on T1.customer_ID=T2.customer_identity
order by T2.number_of_products_ordered, T1.customer_name
like image 484
Andy Avatar asked Jan 18 '23 19:01

Andy


1 Answers

Isn't that what you are looking for? Seems to be a little bit simpler. Tested it on SQL Server - works fine.

SELECT customer_name, COUNT(DISTINCT product_ID) as products_count FROM customer_table
INNER JOIN orders_table ON customer_table.customer_ID = orders_table.customer_ID
GROUP BY customer_table.customer_ID, customer_name
HAVING COUNT(DISTINCT product_ID) > 10
like image 75
Andrei Avatar answered Feb 26 '23 21:02

Andrei