Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/81.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用SQL查询查找已订购的客户的详细信息>;x类产品_Sql_Count_Group By_Distinct - Fatal编程技术网

使用SQL查询查找已订购的客户的详细信息>;x类产品

使用SQL查询查找已订购的客户的详细信息>;x类产品,sql,count,group-by,distinct,Sql,Count,Group By,Distinct,请注意,我看到过一个类似的问题,但我认为我的问题不同,值得单独提问 假设有一个包含以下表的数据库: 带有customer\u ID(键字段)、customer\u名称的customer\u表 带有订单ID(键字段)、客户ID、产品ID的订单表格 现在假设我想找到订购了10多种不同类型产品的所有客户的姓名,以及他们订购的产品类型的数量。同一产品的多个订单不计算在内 我认为下面的查询应该有效,但有以下问题: 通常允许在“GROUPBY”语句中使用count(distinct xxx)吗 我使用的方法

请注意,我看到过一个类似的问题,但我认为我的问题不同,值得单独提问

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

  • 带有customer\u ID(键字段)、customer\u名称的customer\u表
  • 带有订单ID(键字段)、客户ID、产品ID的订单表格
  • 现在假设我想找到订购了10多种不同类型产品的所有客户的姓名,以及他们订购的产品类型的数量。同一产品的多个订单不计算在内

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

  • 通常允许在“GROUPBY”语句中使用count(distinct 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
    

    你可以做得更简单一些:

    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
    

    这不是你要找的吗?看起来有点简单。在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
    

    通过这种方式,您可以计算orders表中不同的产品id条目,从而报告订购了多少独特的产品。“having”子句确保一旦查询完成,它会过滤掉任何少于10个唯一产品ID订单的内容。但没关系。总的来说,我认为你和安德烈的想法是一样的。如果我用count(distinct o.pid)替换“uniques”,那么查询就可以了。我想我们建议的方法是相同的,只是你忘了包括一个关于订购了多少个不同产品标识的报告,你正在对2个或更多的唯一产品标识进行筛选,而他要求10个或更多。谢谢。因此,诀窍是将customer_名称包含到“groupby”语句中,这样就不需要临时表和额外的连接操作。