【发布时间】:2011-11-11 10:44:10
【问题描述】:
请注意,我看到过类似的查询 here,但认为我的查询不同,值得单独提问。
假设有一个包含以下表的数据库:
- customer_table 和 customer_ID(关键字段)、customer_name
- orders_table 带有 order_ID(关键字段)、customer_ID、product_ID
现在假设我想查找订购了超过 10 种不同类型产品的所有客户的姓名,以及他们订购的产品类型的数量。同一产品的多个订单不计算在内。
我认为下面的查询应该可以,但有以下问题:
- count(distinct xxx) 通常是否允许与“group by”语句一起使用?
- 我使用的方法是标准方法吗?有没有人有更好的想法(例如不涉及临时表)?
以下是我的查询
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
【问题讨论】:
标签: sql count group-by distinct