【问题标题】:Using SQL query to find details of customers who ordered > x types of products使用 SQL 查询查找订购 > x 种产品的客户的详细信息
【发布时间】:2011-11-11 10:44:10
【问题描述】:

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

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

  1. customer_table 和 customer_ID(关键字段)、customer_name
  2. orders_table 带有 order_ID(关键字段)、customer_ID、product_ID

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

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

  1. count(distinct xxx) 通常是否允许与“group by”语句一起使用?
  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

【问题讨论】:

    标签: sql count group-by distinct


    【解决方案1】:

    这不是你要找的吗?好像简单了一点。在 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
    

    【讨论】:

    • 我认为我们建议使用相同的方法,除了您忘记包含订购了多少不同 product_id 的报告,并且您正在对 2 个或更多唯一 product_id 进行过滤,他要求 10或更多。
    • 谢谢。所以诀窍是将 customer_name 包含在“group by”语句中,这样就不需要临时表和额外的连接操作。
    【解决方案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
    

    【讨论】:

    • 这样您就可以在订单表中计算不同的产品 ID 条目,从而报告订购了多少独特的产品。 “have”子句确保查询完成后,它会过滤掉所有唯一产品 ID 订单少于 10 个的订单。
    • 由于某种原因,该语句在 Oracle 中不起作用。但是没关系。我认为你和安德烈有同样的想法。如果我用 count(distinct o.pid) 替换 'uniques' 则查询有效。
    猜你喜欢
    • 1970-01-01
    • 2015-12-25
    • 2021-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-30
    • 1970-01-01
    • 2016-05-14
    相关资源
    最近更新 更多