使用SQL查询查找订购客户的详细信息> x类产品

时间:2011-09-06 15:26:26

标签: sql count group-by distinct

请注意,我看到过类似的查询here,但我认为我的查询不同,值得单独提问。

假设有一个包含以下表格的数据库:

  1. customer_table with customer_ID(key field),customer_name
  2. orders_table,包含order_ID(关键字段),customer_ID,product_ID
  3. 现在假设我想找到订购了10种以上不同类型产品的所有客户的名称,以及他们订购的产品类型的数量。同一产品的多个订单不计算在内。

    我认为下面的查询应该有效,但有以下问题:

    1. 使用count(distinct xxx)通常是否允许使用“group by”语句?
    2. 我使用的标准方法是什么?有没有人有更好的想法(例如,不涉及临时表)?
    3. 以下是我的查询

      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
      

2 个答案:

答案 0 :(得分:5)

这不是你想要的吗?似乎有点简单。在SQL Server上测试它 - 工作正常。

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

答案 1 :(得分:2)

你可以更简单地做到:

select

    c.id,
    c.cname,
    count(distinct o.pid) as `uniques`

from o join c
on c.id = o.cid

group by c.id

having `uniques` > 10