如何找到每个客户的不同手机数量,并根据计数将客户(计数)放在不同的存储桶中?

时间:2018-02-22 12:52:13

标签: sql oracle buckets

下面是我有customer_id和他们拥有的不同手机的表格。

customer_id     phone_number
101            123456789
102            234567891
103            345678912
102            456789123
101            567891234
104            678912345
105            789123456
106            891234567
106            912345678
106            456457234
101            655435664
107            453426782

现在,我想查找customer_id和不同的电话号码 所以我使用了这个查询:

select distinct customer_id ,count(distinct phone_number)
from customer_phone;

customer_id   no of phones
101            3
102            2
103            1
104            1
105            1
106            3
107            1

而且,从上表中我的最终目标是实现以下输出,该输出将计数和放入不同的存储桶,然后计算属于这些存储桶的消费者数量。

Buckets no of consumers
3         2
2         1
1         4

有近2亿条记录。能否解释一下解决这个问题的有效方法?

2 个答案:

答案 0 :(得分:1)

您可以使用width_bucket

select bucket, count(*)
from (
  select width_bucket(count(distinct phone_number), 1, 10, 10) as bucket
  from customer_phone
  group by customer_id
) t
group by bucket;

width_bucket(..., 1, 10, 10)为值1到10创建10个桶。

在线示例:http://dbfiddle.uk/?rdbms=oracle_11.2&fiddle=1e6d55305570499f363837aba21bdc7e

答案 1 :(得分:0)

使用两个聚合:

select cnt, count(*), min(customer_id), max(customer_id)
from (select customer_id, count(distinct phone_number) as cnt
      from customer_phone
      group by customer_id
     ) c
group by cnt
order by cnt;