【问题标题】:count multiple attributes sql计算多个属性sql
【发布时间】:2012-11-13 13:35:09
【问题描述】:

我正在寻找以下输出

  • 10 位客户在 2 个产品组中购买了 10 件商品
  • 8 位客户在 1 个产品组中购买了 10 件商品。

通常是一个矩阵,其中客户数量超过购买的商品和产品组,即。计算超过 2 个属性(项目和产品组)

我尝试了下面的代码,但它只给了我

  • 1 位客户拥有 10 个项目和 2 个产品组
  • 1 位客户拥有 10 件商品和 1 个产品组,尽管每行的客户更多:

sn-p,

count (distinct customer_id) over (Partition by customer_id) as Customer_ID
,count (distinct customer_shipment_item_id) Over (Partition by customer_id) as customer_items
,count (distinct product_group) Over (Partition by customer_id) as customer_product_groups

您能解释一下这是如何工作的吗?

【问题讨论】:

  • 如果您提供架构和数据示例会更容易,SQL Fiddle 可能是
  • 嗨 Roman,我可以在这里添加一张桌子吗?每次我尝试添加一些 excel 示例时,格式都会中断。谢谢比安卡

标签: mysql sql


【解决方案1】:

试试这个。除非我不明白您在寻找什么,否则您不需要 Partition By 子句。

count (distinct customer_id) as Customer_ID
,count (distinct customer_shipment_item_id) as customer_items
,count (distinct product_group) as customer_product_groups

【讨论】:

  • 嗨,汤姆,谢谢,但这没有用。结果是一行有 x 个客户、y 个项目、z 个产品组。不过,我正在寻找一个矩阵,按客户计数:x 客户与 y1 产品、z1 产品组的组合、x 客户与 y2 产品、z2 产品组的组合等等。有任何想法吗?比安卡
【解决方案2】:

我认为这样的东西会给你你正在寻找的东西:

SELECT    COUNT(customer_id) Customer_ID, customer_items, customer_product_groups

FROM 

(SELECT   customer_id, COUNT(DISTINCT customer_shipment_item_id) as customer_items,
          COUNT(DISTINCT product_group) as customer_product_groups
 FROM     TABLENAME
          JOIN <YOUR JOINS>
 WHERE    customer_id IN (SELECT customer_ID FROM <YOUR JOINS> WHERE customer_shipment_item_id = x)
 GROUP BY customer_id
) a

GROUP BY customer_items, customer_product_groups

【讨论】:

  • 嗨,汤姆,谢谢,实际上它现在有效,但由于这只是问题的一部分,所以总的结果仍然无效(我的错,刚刚意识到):完整的问题实际上是,客户如何看起来就像客户在哪里购买了符合特定标准的一件或多件商品。因此,我将查询限制为此标准(customer_shipment_item_id =x)。现在,我只得到客户的一部分,即标准属于该项目的部分,而不是他/她的整体外观(只有一个项目可能符合标准)。这有意义吗?
  • 我刚刚更新了代码,在子查询中添加了 WHERE 子句。这将为具有您正在寻找的 customer_shipment_item_id 的客户提供完全相同的结果。
猜你喜欢
  • 2018-10-13
  • 2020-05-17
  • 1970-01-01
  • 1970-01-01
  • 2017-08-31
  • 2015-05-17
  • 1970-01-01
  • 2022-06-23
  • 2019-12-29
相关资源
最近更新 更多