0

假设我有一个包含以下列的表:

客户 ID、产品 ID

我想看到的是,如果我有 100,000 个客户,我想对他们进行分组,这样我就可以看到 X 个客户有 Y 个产品。例如,2,000 个客户可能有 5 个购买,1,000 个客户可能有 4 个产品,10 个客户可能有 25 个产品,等等。我如何根据客户数量对 X 个产品进行分组?

数据库是甲骨文。

样本数据集:

customerID  productId
---------- ----------
 12345      33035
 12345      33049
 12345      33054
 56789      32777
 56789      32897
 56789      32928
 56789      32958
 56789      33174
 56789      33175
 56789      33410
 56789      35101
 67890      32777
 67890      32897
 67890      32928
 67890      32958
 67890      33174
 67890      33175
 67890      33410
 67890      35101
  45678      33035
  45678      33289
  45678      34354
  45678      36094
 23456      32778
 23456      33047
 23456      33051
 34567      32776
 34567      32778
 34567      33162

这导致了这个分组(基于示例数据集),其中有 3 名客户拥有 3 种产品,2 名客户拥有 8 种产品,1 名客户拥有 4 种产品。

number_customers    number_products
3           3
2           8
1           4

我尝试了一堆 group by 语句,但我遗漏了一些东西。任何帮助将不胜感激。

谢谢

4

3 回答 3

2
SELECT
  COUNT(CustomerID) AS number_customers,
  number_products
FROM (
  SELECT CustomerID, 
  COUNT(ProductID) AS number_products
  FROM tableName
  GROUP BY customerID
) subquery
GROUP BY number_products
于 2013-07-10T21:28:00.297 回答
0
Select CustomerID, count(ProductID)
FROM tableName
group by customerID
having count(ProductID) > 25

现在,如果您只想计算不同的产品...

   Select CustomerID, count(distinct ProductID)
    FROM tableName
    group by customerID
    having count(ProductID) > 25

假设您的数据包含每个产品每次列出的客户 1,并且多个客户可能与同一产品相关联。

于 2013-07-10T21:16:14.527 回答
0
create table cust_pur as select floor(dbms_random.value(1,21)) customer_id,         floor(dbms_random.value(1,21)) product_id from dual connect by level <= 100 order by customer_id

select * from cust_pur order by customer_id


with k1 as (
select distinct(customer_id), count(product_id)  over ( partition by customer_id ) cnt from cust_pur order by customer_id
)
select count(customer_id),cnt from k1 group by cnt
于 2013-07-10T23:45:16.820 回答