请注意,我看到类似的查询here,但认为我的查询不同于另外的问题。使用SQL查询来查找订购了> x类型产品的客户的详细信息
假设有是具有以下表的数据库:
- CUSTOMER_TABLE与CUSTOMER_ID(关键字段),CUSTOMER_NAME
- orders_table与ORDER_ID(关键字段),CUSTOMER_ID,PRODUCT_ID
现在假设我想查找所有已订购超过10种不同类型产品的客户的名称以及他们订购的产品类型的数量。同一产品的多个订单不计算在内。
我觉得下面的查询应该工作,但有以下问题:
- 是使用次数(不同的XXX)的一般允许与语句“按组”?
- 我使用标准方法吗?有没有人有更好的想法(例如不涉及临时表)?
下面是我的查询
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
我认为我们建议采用相同的方法,只是您忘记包含订购了多少个不同product_ids的报告,并且您正在对两个或更多个唯一product_id进行筛选,并在其中请求10个或更多个product_id。 –
谢谢。所以诀窍是将customer_name包含在“group by”语句中,从而不再需要临时表和额外的联接操作。 – Andy