SQL

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

发布于 2021-03-27 16:55:16

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

  1. 带customer_ID(键字段),customer_name的customer_table
  2. 带order_ID(键字段),customer_ID,product_ID的orders_table

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

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

  1. 通常在“ group by”语句中允许使用count(distinct 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
关注者
0
被浏览
623
1 个回答
  • 面试哥
    面试哥 2021-03-27
    为面试而生,有面试问题,就找面试哥。

    那不是您要找的东西吗?似乎要简单一些。在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
    


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看