2011-09-06 161 views
1

请注意,我看到类似的查询here,但认为我的查询不同于另外的问题。使用SQL查询来查找订购了> x类型产品的客户的详细信息

假设有是具有以下表的数据库:

  1. CUSTOMER_TABLE与CUSTOMER_ID(关键字段),CUSTOMER_NAME
  2. orders_table与ORDER_ID(关键字段),CUSTOMER_ID,PRODUCT_ID

现在假设我想查找所有已订购超过10种不同类型产品的客户的名称以及他们订购的产品类型的数量。同一产品的多个订单不计算在内。

我觉得下面的查询应该工作,但有以下问题:

  1. 是使用次数(不同的XXX)的一般允许与语句“按组”?
  2. 我使用标准方法吗?有没有人有更好的想法(例如不涉及临时表)?

下面是我的查询

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 

回答

3

是不是你在找什么?似乎有点简单。在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 
+0

我认为我们建议采用相同的方法,只是您忘记包含订购了多少个不同product_ids的报告,并且您正在对两个或更多个唯一product_id进行筛选,并在其中请求10个或更多个product_id。 –

+0

谢谢。所以诀窍是将customer_name包含在“group by”语句中,从而不再需要临时表和额外的联接操作。 – Andy

1

你可以做到这一点更简单地说:

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 
+0

这样您就可以统计订单表中的不同产品ID条目,从而报告订购了多少独特产品。 “having”子句确保查询完成后,它会过滤掉少于10个唯一产品ID订单的任何东西。 –

+0

由于某种原因,该声明在Oracle中不起作用。但是不要紧。我认为你和安德烈有一样的想法。如果我用count(distinct o.pid)替换'uniques',那么查询就可以工作。 – Andy

相关问题